

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/fluid.png">
  <link rel="icon" href="/blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Vincent">
  <meta name="keywords" content="">
  
    <meta name="description" content="Elasticsearch第一章 Elasticsearch 概述1.1 Elasticsearch 是什么​		The Elastic Stack, 包括 Elasticsearch、Kibana、Beats 和 Logstash（也称为 ELK Stack）。 能够安全可靠地获取任何来源、任何格式的数据，然后实时地对数据进行搜索、分析和可视化。Elaticsearch，简称为 ES，ES 是一">
<meta property="og:type" content="article">
<meta property="og:title" content="ElasticSearch">
<meta property="og:url" content="https://zqystudy.gitee.io/blog/2022/08/09/ElasticSearch/index.html">
<meta property="og:site_name" content="Vincent">
<meta property="og:description" content="Elasticsearch第一章 Elasticsearch 概述1.1 Elasticsearch 是什么​		The Elastic Stack, 包括 Elasticsearch、Kibana、Beats 和 Logstash（也称为 ELK Stack）。 能够安全可靠地获取任何来源、任何格式的数据，然后实时地对数据进行搜索、分析和可视化。Elaticsearch，简称为 ES，ES 是一">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://zqystudy.gitee.io/blog/img/ElasticSearch_logo.png">
<meta property="article:published_time" content="2022-08-09T06:37:23.000Z">
<meta property="article:modified_time" content="2022-11-25T02:29:56.015Z">
<meta property="article:author" content="Vincent">
<meta property="article:tag" content="搜索引擎">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://zqystudy.gitee.io/blog/img/ElasticSearch_logo.png">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>ElasticSearch - Vincent</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/blog/css/highlight-dark.css" />
  



  
<link rel="stylesheet" href="/blog/css/mac.css">
<link rel="stylesheet" href="/blog/css/custom.css">



  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"zqystudy.gitee.io","root":"/blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":true,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":true,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"zc2OPBTVjL4nIWcxAdu9fkZp-gzGzoHsz","app_key":"vpIXqlueEoj5yt2RfIa84WzG","server_url":"https://zc2opbtv.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":false},"statistics":{"enable":true,"source":"leancloud","pv_format":"总访问量 {} 次","uv_format":"总访客数 {} 人"}},"search_path":"/blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
  

  

  

  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/blog/">
      <strong>VincentのBlog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/talking/">
                <i class="iconfont icon-kakao-talk-fill"></i>
                talking
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/blog/img/banner.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="ElasticSearch"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        Vincent
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-08-09 14:37" pubdate>
          2022年8月9日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          83k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          694 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span>次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar category-bar" style="margin-right: -1rem">
    





<div class="category-list">
  
  
    
    
    
    <div class="category row nomargin-x">
      <a class="category-item 
          list-group-item category-item-action col-10 col-md-11 col-xm-11" title="学习笔记"
        id="heading-078425eaf316a180b0989442e53f920b" role="tab" data-toggle="collapse" href="#collapse-078425eaf316a180b0989442e53f920b"
        aria-expanded="true"
      >
        学习笔记
        <span class="list-group-count">(5)</span>
        <i class="iconfont icon-arrowright"></i>
      </a>
      
      <div class="category-collapse collapse show" id="collapse-078425eaf316a180b0989442e53f920b"
           role="tabpanel" aria-labelledby="heading-078425eaf316a180b0989442e53f920b">
        
        
          
  <div class="category-post-list">
    
    
      
      
        <a href="/blog/2022/08/09/ElasticSearch/" title="ElasticSearch"
           class="list-group-item list-group-item-action
           active">
          <span class="category-post">ElasticSearch</span>
        </a>
      
    
      
      
        <a href="/blog/2022/11/03/Lambda%E8%A1%A8%E8%BE%BE%E5%BC%8F/" title="Lambda表达式"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">Lambda表达式</span>
        </a>
      
    
      
      
        <a href="/blog/2022/11/03/%E5%86%85%E9%83%A8%E7%B1%BB/" title="内部类"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">内部类</span>
        </a>
      
    
      
      
        <a href="/blog/2022/10/18/%E7%AC%AC%E4%B8%80%E7%AB%A0%20Elasticsearch%E6%A6%82%E8%BF%B0/" title="第一章 Elasticsearch概述"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">第一章 Elasticsearch概述</span>
        </a>
      
    
      
      
        <a href="/blog/2022/11/25/%E7%AC%AC%E4%BA%8C%E7%AB%A0%20ElasticSearch%E5%85%A5%E9%97%A8/" title="第二章 ElasticSearch 入门"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">第二章 ElasticSearch 入门</span>
        </a>
      
    
  </div>

        
      </div>
    </div>
  
</div>


  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">ElasticSearch</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2022年11月25日 上午
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="Elasticsearch"><a href="#Elasticsearch" class="headerlink" title="Elasticsearch"></a>Elasticsearch</h1><h2 id="第一章-Elasticsearch-概述"><a href="#第一章-Elasticsearch-概述" class="headerlink" title="第一章 Elasticsearch 概述"></a>第一章 Elasticsearch 概述</h2><h3 id="1-1-Elasticsearch-是什么"><a href="#1-1-Elasticsearch-是什么" class="headerlink" title="1.1 Elasticsearch 是什么"></a>1.1 Elasticsearch 是什么</h3><p>​		The Elastic Stack, 包括 Elasticsearch、Kibana、Beats 和 Logstash（也称为 ELK Stack）。 能够安全可靠地获取任何来源、任何格式的数据，然后实时地对数据进行搜索、分析和可视化。<strong>Elaticsearch</strong>，简称为 ES，<strong>ES 是一个开源的高扩展的分布式全文搜索引擎</strong>，是整个 Elastic  Stack 技术栈的核心。它可以近乎实时的存储、检索数据；本身扩展性很好，可以扩展到上百台服务器，处理 PB 级别的数据。</p>
<h3 id="1-2-全文搜索引擎"><a href="#1-2-全文搜索引擎" class="headerlink" title="1.2 全文搜索引擎"></a>1.2 全文搜索引擎</h3><p>​		Google，百度类的网站搜索，它们都是根据网页中的关键字生成索引，我们在搜索的时 候输入关键字，它们会将该关键字即索引匹配到的所有网页返回；还有常见的项目中应用日志的搜索等等。对于这些非结构化的数据文本，关系型数据库搜索不是能很好的支持。 </p>
<p>​		一般传统数据库，全文检索都实现的很鸡肋，因为一般也没人用数据库存文本字段。进行全文检索需要扫描整个表，如果数据量大的话即使对 SQL 的语法优化，也收效甚微。建立了索引，但是维护起来也很麻烦，对于 insert 和 update 操作都会重新构建索引。</p>
<p>​		基于以上原因可以分析得出，在一些生产环境中，使用常规的搜索方式，性能是非常差的：</p>
<ul>
<li>搜索的数据对象是大量的非结构化的文本数据。</li>
<li>文件记录量达到数十万或数百万个甚至更多。</li>
<li>支持大量基于交互式文本的查询。</li>
<li>需求非常灵活的全文搜索查询。 对高度相关的搜索结果的有特殊需求，但是没有可用的关系数据库可以满足。</li>
<li>对不同记录类型、非文本数据操作或安全事务处理的需求相对较少的情况。</li>
</ul>
<p>为了解决<strong>结构化数据搜索</strong>和<strong>非结构化数据搜索</strong>性能问题，我们就需要专业，健壮，强大的<strong>全文搜索引擎</strong></p>
<p>​		这里说到的全文搜索引擎指的是目前广泛应用的主流搜索引擎。它的<strong>工作原理</strong>是计算机索引程序通过扫描文章中的每一个词，对每一个词建立一个索引，指明该词在文章中出现的 次数和位置，当用户查询时，检索程序就根据事先建立的索引进行查找，并将查找的结果反 馈给用户的检索方式。这个过程类似于通过字典中的检索字表查字的过程。</p>
<h3 id="1-3-Elasticsearch-And-Solr"><a href="#1-3-Elasticsearch-And-Solr" class="headerlink" title="1.3 Elasticsearch And Solr"></a>1.3 Elasticsearch And Solr</h3><p>​		Lucene 是 Apache 软件基金会 Jakarta 项目组的一个子项目，提供了一个简单却强大的应用程式接口，能够做全文索引和搜寻。在 Java 开发环境里 Lucene 是一个成熟的免费开源工具。就其本身而言，Lucene 是当前以及最近几年最受欢迎的免费 Java 信息检索程序库。 但 Lucene 只是一个提供全文搜索功能类库的核心工具包，而真正使用它还需要一个完善的服务框架搭建起来进行应用。</p>
<p>​		目前市面上流行的搜索引擎软件，主流的就两款：<strong>Elasticsearch 和 Solr</strong>,这两款都是基 于 Lucene 搭建的，可以独立部署启动的搜索引擎服务软件。由于内核相同，所以两者<strong>除了服务器安装、部署、管理、集群以外，对于数据的操作修改、添加、保存、查询等等都十分类似</strong>。</p>
<p>​		在使用过程中，一般都会将 Elasticsearch 和 Solr 这两个软件对比，然后进行选型。这两个搜索引擎都是流行的，先进的的开源搜索引擎。它们都是围绕核心底层搜索库 - Lucene 构建的 - 但它们又是不同的。像所有东西一样，每个都有其优点和缺点：</p>
<p><img src="https://img-blog.csdnimg.cn/069a5a32293a4cbe863934646514b5a3.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808095742880"></p>
<h3 id="1-4-Elasticsearch-Or-Solr"><a href="#1-4-Elasticsearch-Or-Solr" class="headerlink" title="1.4 Elasticsearch Or Solr"></a>1.4 Elasticsearch Or Solr</h3><p>Elasticsearch 和 Solr 都是开源搜索引擎，那么我们在使用时该如何选择呢？</p>
<ul>
<li><p>Google 搜索趋势结果表明，与 Solr 相比，Elasticsearch 具有很大的吸引力，但这并不意味着 Apache Solr 已经死亡。虽然有些人可能不这么认为，但 Solr 仍然是最受欢迎的搜索引擎之一，拥有强大的社区和开源支持。</p>
</li>
<li><p>与 Solr 相比，Elasticsearch 易于安装且非常轻巧。此外，你可以在几分钟内安装并运行 Elasticsearch。但是，如果 Elasticsearch 管理不当，这种易于部署和使用可能会成为一个问题。基于 JSON 的配置很简单，但如果要为文件中的每个配置指定注释，那么它不适合您。总的来说，<strong>如果你的应用使用的是 JSON，那么 Elasticsearch 是一个更好的选择。 否则，请使用 Solr，因为它的 schema.xml 和 solrconfig.xml 都有很好的文档记录。</strong></p>
</li>
<li><p>Solr 拥有更大，更成熟的用户，开发者和贡献者社区。ES 虽拥有的规模较小但活跃的 用户社区以及不断增长的贡献者社区。 </p>
<p>Solr 贡献者和提交者来自许多不同的组织，而 Elasticsearch 提交者来自单个公司。</p>
</li>
<li><p>Solr 更成熟，但 ES 增长迅速，更稳定。 </p>
</li>
<li><p>Solr 是一个非常有据可查的产品，具有清晰的示例和 API 用例场景。 Elasticsearch 的 文档组织良好，但它缺乏好的示例和清晰的配置说明。</p>
</li>
</ul>
<p>​		<strong>那么，到底是 Solr 还是 Elasticsearch？</strong> </p>
<p>​		有时很难找到明确的答案。无论您选择 Solr 还是 Elasticsearch，首先需要<strong>了解正确的用例和未来需求</strong>。总结他们的每个属性。</p>
<ul>
<li>由于易于使用，Elasticsearch 在新开发者中更受欢迎。一个下载和一个命令就可以启动一切。</li>
<li>如果除了搜索文本之外还需要它来<strong>处理分析查询</strong>，Elasticsearch 是更好的选择</li>
<li>如果需要<strong>分布式索引</strong>，则需要选择 Elasticsearch。对于<strong>需要良好可伸缩性和以及性能分布式环境</strong>，Elasticsearch 是更好的选择。</li>
<li>Elasticsearch 在开源日志管理用例中占据主导地位，许多组织在Elasticsearch 中索引它们的日志以使其可搜索。</li>
<li>如果你<strong>喜欢监控和指标</strong>，那么请使用 Elasticsearch，因为相对于 Solr，Elasticsearch 暴露了更多的关键指标</li>
</ul>
<h3 id="1-5-Elasticsearch-应用案例"><a href="#1-5-Elasticsearch-应用案例" class="headerlink" title="1.5 Elasticsearch 应用案例"></a>1.5 Elasticsearch 应用案例</h3><ul>
<li><strong>GitHub</strong>: 2013 年初，抛弃了 Solr，采取 Elasticsearch 来做 PB 级的搜索。“GitHub 使用 Elasticsearch 搜索 20TB 的数据，包括 13 亿文件和 1300 亿行代码”。</li>
<li><strong>维基百科</strong>：启动以 Elasticsearch 为基础的核心搜索架构 </li>
<li><strong>SoundCloud</strong>：“SoundCloud 使用 Elasticsearch 为 1.8 亿用户提供即时而精准的音乐搜索服务”。</li>
<li><strong>百度</strong>：目前广泛使用 Elasticsearch 作为文本数据分析，采集百度所有服务器上的各类指 标数据及用户自定义数据，通过对各种数据进行多维分析展示，辅助定位分析实例异常 或业务层面异常。目前覆盖百度内部 20 多个业务线（包括云分析、网盟、预测、文库、 直达号、钱包、风控等），单集群最大 100 台机器，200 个 ES 节点，每天导入 30TB+ 数据。</li>
<li><strong>新浪</strong>：使用 Elasticsearch 分析处理 32 亿条实时日志。</li>
<li><strong>阿里</strong>：使用 Elasticsearch 构建日志采集和分析体系。</li>
<li><strong>Stack Overflow</strong>：解决 Bug 问题的网站，全英文，编程人员交流的网站。</li>
</ul>
<h2 id="第二章-ElasticSearch-入门"><a href="#第二章-ElasticSearch-入门" class="headerlink" title="第二章 ElasticSearch 入门"></a>第二章 ElasticSearch 入门</h2><h3 id="2-1-ElasticSearch-安装"><a href="#2-1-ElasticSearch-安装" class="headerlink" title="2.1 ElasticSearch 安装"></a>2.1 ElasticSearch 安装</h3><h4 id="2-1-1-下载软件"><a href="#2-1-1-下载软件" class="headerlink" title="2.1.1 下载软件"></a>2.1.1 下载软件</h4><p>​		Elasticsearch 的官方地址：<a target="_blank" rel="noopener" href="https://www.elastic.co/cn/">https://www.elastic.co/cn/</a></p>
<p>​		Elasticsearch 分为 Linux 和 Windows 版本，基于我们主要学习的是 Elasticsearch 的 Java 客户端的使用，使用的是安装较为简便的 Windows 版本。本次选择的是7.8.0 版本</p>
<p>​		下载地址：：<a target="_blank" rel="noopener" href="https://www.elastic.co/cn/downloads/past-releases#elasticsearch">https://www.elastic.co/cn/downloads/past-releases#elasticsearch</a></p>
<h4 id="2-1-2-安装软件"><a href="#2-1-2-安装软件" class="headerlink" title="2.1.2 安装软件"></a>2.1.2 安装软件</h4><p>​		Windows 版的 Elasticsearch 的安装很简单，解压即安装完毕，解压后的 Elasticsearch 的 目录结构如下，由于我的电脑已经使用过Elasticsearch，所以目录结构比初始的多了个data目录，log中也多了点日志文件。</p>
<p><img src="https://img-blog.csdnimg.cn/4f8d84c1f9364899b1c16866bb2aafda.png" srcset="/blog/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<table>
<thead>
<tr>
<th>目录</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>bin</td>
<td>可执行脚本目录</td>
</tr>
<tr>
<td>config</td>
<td>配置目录</td>
</tr>
<tr>
<td>jdk</td>
<td>内置JDK目录</td>
</tr>
<tr>
<td>lib</td>
<td>类库</td>
</tr>
<tr>
<td>logs</td>
<td>日志目录</td>
</tr>
<tr>
<td>modules</td>
<td>模块目录</td>
</tr>
<tr>
<td>plugin</td>
<td>插件目录</td>
</tr>
</tbody></table>
<p><strong>解压后，进入 bin 文件目录，点击 elasticsearch.bat 文件启动 ES 服务</strong></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808101944791.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808101944791"></p>
<p><strong>注意：9300端口为ElasticSearch集群间的通信端口。9200端口为浏览器访问的http协议RESTful端口。</strong></p>
<p>​	打开浏览器（推荐使用谷歌浏览器），输入地址：<a href="http://localhost:9200，测试结果">http://localhost:9200，测试结果</a></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808102201536.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808102201536"></p>
<h4 id="2-1-3-问题解决"><a href="#2-1-3-问题解决" class="headerlink" title="2.1.3 问题解决"></a>2.1.3 问题解决</h4><ul>
<li>Elasticsearch 是使用 java 开发的，且 7.8 版本的 ES 需要 JDK 版本 1.8 以上，默认安装 包带有 jdk 环境，如果系统配置 JAVA_HOME，那么使用系统默认的 JDK，如果没有配置使用自带的 JDK，一般建议使用系统配置的 JDK。</li>
<li>双击启动窗口闪退，通过路径访问追踪错误，如果是“空间不足”，请修改 config&#x2F;jvm.options 配置文件</li>
</ul>
<figure class="highlight ldif"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs ldif"><span class="hljs-comment"># 设置 JVM 初始内存为 1G。此值可以设置与-Xmx 相同，以避免每次垃圾回收完成后 JVM 重新分配内存</span><br><span class="hljs-comment"># Xms represents the initial size of total heap space</span><br><span class="hljs-comment"># 设置 JVM 最大可用内存为 1G</span><br><span class="hljs-comment"># Xmx represents the maximum size of total heap space</span><br><br><span class="hljs-literal">-</span>Xms1g<br><span class="hljs-literal">-</span>Xmx1g<br><br></code></pre></td></tr></table></figure>

<h3 id="2-2-Elasticsearch-基本操作"><a href="#2-2-Elasticsearch-基本操作" class="headerlink" title="2.2 Elasticsearch 基本操作"></a>2.2 Elasticsearch 基本操作</h3><h4 id="2-2-1-RESTful"><a href="#2-2-1-RESTful" class="headerlink" title="2.2.1 RESTful"></a>2.2.1 RESTful</h4><p>​		<strong>REST 指的是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就 是 RESTful。</strong>Web 应用程序最重要的 REST 原则是，客户端和服务器之间的交互在请求之 间是无状态的。从客户端到服务器的每个请求都必须包含理解请求所必需的信息。如果服务器在请求之间的任何时间点重启，客户端不会得到通知。此外，无状态请求可以由任何可用服务器回答，这<strong>十分适合云计算之类的环境</strong>。客户端可以缓存数据以改进性能。</p>
<p>​		在服务器端，应用程序状态和功能可以分为各种资源。资源是一个有趣的概念实体，它向客户端公开。资源的例子有：应用程序对象、数据库记录、算法等等。每个资源都使用 URI  (Universal Resource Identifier) 得到一个唯一的地址。所有资源都共享统一的接口，以便在客户端和服务器之间传输状态。使用的是标准的 HTTP 方法，比如 GET、PUT、POST 和 DELETE。</p>
<p>​		 在 REST 样式的 Web 服务中，每个资源都有一个地址。资源本身都是方法调用的目标，方法列表对所有资源都是一样的。这些方法都是标准方法，包括 HTTP GET、POST、 PUT、DELETE，还可能包括 HEAD 和 OPTIONS。简单的理解就是，如果想要访问互联网上的资源，就必须向资源所在的服务器发出请求，请求体中必须包含资源的网络路径，以及对资源进行的操作(增删改查)。</p>
<h4 id="2-2-2-客户端安装"><a href="#2-2-2-客户端安装" class="headerlink" title="2.2.2 客户端安装"></a>2.2.2 客户端安装</h4><p>​		如果直接通过浏览器向 Elasticsearch 服务器发请求，那么需要在发送的请求中包含 HTTP 标准的方法，而 HTTP 的大部分特性且仅支持 GET 和 POST 方法。所以为了能方便地进行客户端的访问，可以使用 Postman 软件 </p>
<p>​		Postman 是一款强大的网页调试工具，提供功能强大的 Web API 和 HTTP 请求调试。 软件功能强大，界面简洁明晰、操作方便快捷，设计得很人性化。Postman 中文版能够发送 任何类型的 HTTP 请求 (GET, HEAD, POST, PUT..)，不仅能够表单提交，且可以附带任意类型请求体。</p>
<p>​		Postman 官网：<a target="_blank" rel="noopener" href="https://www.getpostman.com/">https://www.getpostman.com</a> </p>
<p>​		Postman 下载：<a target="_blank" rel="noopener" href="https://www.getpostman.com/apps">https://www.getpostman.com/apps</a></p>
<h4 id="2-2-3-数据格式"><a href="#2-2-3-数据格式" class="headerlink" title="2.2.3 数据格式"></a>2.2.3 数据格式</h4><p>​		Elasticsearch 是<strong>面向文档型数据库</strong>，一条数据在这里就是一个文档。为了方便大家理解， 我们将 Elasticsearch 里存储文档数据和关系型数据库 MySQL 存储数据的概念进行一个类比</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808103003998.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808103003998"></p>
<p>ES 里的 Index 可以看做一个库，而 Types 相当于表，Documents 则相当于表的行。 这里 Types 的概念已经被逐渐弱化，Elasticsearch 6.X 中，一个 index 下已经只能包含一个 type，Elasticsearch 7.X 中, Type 的概念已经被删除了。</p>
<pre><code class="hljs">     用 JSON 作为文档序列化的格式，比如一条用户信息：
</code></pre>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br> <span class="hljs-attr">&quot;name&quot;</span> <span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;John&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;sex&quot;</span> <span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;Male&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;age&quot;</span> <span class="hljs-punctuation">:</span> <span class="hljs-number">25</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;birthDate&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1990/05/01&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;about&quot;</span> <span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;I love to go rock climbing&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;interests&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> <span class="hljs-string">&quot;sports&quot;</span><span class="hljs-punctuation">,</span> <span class="hljs-string">&quot;music&quot;</span> <span class="hljs-punctuation">]</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h4 id="2-2-4-HTTP-操作"><a href="#2-2-4-HTTP-操作" class="headerlink" title="2.2.4 HTTP 操作"></a>2.2.4 HTTP 操作</h4><h5 id="2-2-4-1-索引操作"><a href="#2-2-4-1-索引操作" class="headerlink" title="2.2.4.1 索引操作"></a>2.2.4.1 索引操作</h5><h6 id="1-创建索引"><a href="#1-创建索引" class="headerlink" title="1.创建索引"></a>1.创建索引</h6><p>对比关系型数据库，创建索引就等同于创建数据库 在 Postman 中，向 ES 服务器发 <strong>PUT</strong> 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/shopping">http://127.0.0.1:9200/shopping</a></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808103450032.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808103450032"></p>
<p>请求后，服务器返回响应</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808103529839.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808103529839"></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br> <span class="hljs-string">&quot;acknowledged&quot;</span>【响应结果】<span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span> # <span class="hljs-literal"><span class="hljs-keyword">true</span></span> 操作成功<br> <span class="hljs-string">&quot;shards_acknowledged&quot;</span>【分片结果】<span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span> # 分片操作成功<br> <span class="hljs-string">&quot;index&quot;</span>【索引名称】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;shopping&quot;</span><br><span class="hljs-punctuation">&#125;</span><br># 注意：创建索引库的分片数默认 <span class="hljs-number">1</span> 片，在 <span class="hljs-number">7.0</span><span class="hljs-number">.0</span> 之前的 Elasticsearch 版本中，默认 <span class="hljs-number">5</span> 片<br></code></pre></td></tr></table></figure>

<p>如果重复添加索引，会返回错误信息</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808103812968.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808103812968"></p>
<h6 id="2-查询所有索引"><a href="#2-查询所有索引" class="headerlink" title="2.查询所有索引"></a>2.查询所有索引</h6><p>在 Postman 中，向 ES 服务器发 GET 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/_cat/indices?v">http://127.0.0.1:9200/_cat/indices?v</a></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808105425358.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808105425358"></p>
<p>这里请求路径中的**_ca<strong>t 表示查看的意思，</strong>indices** 表示索引，所以整体含义就是查看当前 ES 服务器中的所有索引，就好像 MySQL 中的 show tables 的感觉，服务器响应结果如下</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808105443190.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808105443190"></p>
<table>
<thead>
<tr>
<th>表头</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>health</td>
<td>当前服务器健康状态：$\textcolor{green}{green}$（集群完整） $\textcolor{yellow}{yellow}$(单点正常，集群不完整) $\textcolor{red}{red}$（单点不正常）</td>
</tr>
<tr>
<td>status</td>
<td>索引打开、关闭状态</td>
</tr>
<tr>
<td>index</td>
<td>索引名</td>
</tr>
<tr>
<td>uuid</td>
<td>索引统一编号</td>
</tr>
<tr>
<td>pri</td>
<td>主分片数量</td>
</tr>
<tr>
<td>rep</td>
<td>副本数量</td>
</tr>
<tr>
<td>docs.count</td>
<td>可用文档数量</td>
</tr>
<tr>
<td>docs.deleted</td>
<td>文档删除状态（逻辑删除）</td>
</tr>
<tr>
<td>store.size</td>
<td>主分片和副分片整体占空间大小</td>
</tr>
<tr>
<td>pri.store.size</td>
<td>主分片占空间大小</td>
</tr>
</tbody></table>
<h6 id="3-查看单个索引"><a href="#3-查看单个索引" class="headerlink" title="3.查看单个索引"></a>3.查看单个索引</h6><p>在 Postman 中，向 ES 服务器发 GET 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/shopping">http://127.0.0.1:9200/shopping</a></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808132806592.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808132806592"></p>
<p>查看索引向 ES 服务器发送的请求路径和创建索引是一致的。但是 HTTP 方法不一致。这里 可以体会一下 RESTful 的意义， 请求后，服务器响应结果如下：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808133828433.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808133828433"></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-string">&quot;shopping&quot;</span>【索引名】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-string">&quot;aliases&quot;</span>【别名】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-string">&quot;mappings&quot;</span>【映射】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-string">&quot;settings&quot;</span>【设置】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>            <span class="hljs-string">&quot;index&quot;</span>【设置-索引】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>                <span class="hljs-string">&quot;creation_date&quot;</span>【设置-索引-创建时间】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1659926095568&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-string">&quot;number_of_shards&quot;</span>【设置 - 索引 - 主分片数量】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-string">&quot;number_of_replicas&quot;</span>【设置 - 索引 - 副分片数量】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-string">&quot;uuid&quot;</span>【设置 - 索引 - 唯一标识】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;99pOhKG0RDi-Vk7ezUKIdQ&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-string">&quot;version&quot;</span>【设置 - 索引 - 版本】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>                    <span class="hljs-attr">&quot;created&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;7080099&quot;</span><br>                <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-string">&quot;provided_name&quot;</span>【设置 - 索引 - 名称】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;shopping&quot;</span><br>            <span class="hljs-punctuation">&#125;</span><br>        <span class="hljs-punctuation">&#125;</span><br>    <span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h6 id="4-删除索引"><a href="#4-删除索引" class="headerlink" title="4.删除索引"></a>4.删除索引</h6><p>在 Postman 中，向 ES 服务器发 DELETE 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/shopping">http://127.0.0.1:9200/shopping</a></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808134227446.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808134227446"></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808134252723.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808134252723"></p>
<p>重新访问索引时，服务器返回响应：索引不存在</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808134354469.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808134354469"></p>
<h5 id="2-2-4-2-文档操作"><a href="#2-2-4-2-文档操作" class="headerlink" title="2.2.4.2 文档操作"></a>2.2.4.2 文档操作</h5><h6 id="1-创建文档"><a href="#1-创建文档" class="headerlink" title="1.创建文档"></a>1.创建文档</h6><p>索引已经创建好了，接下来我们来创建文档，并添加数据。这里的文档可以类比为关系型数据库中的表数据，添加的数据格式为 <strong>JSON</strong> 格式</p>
<p>在 Postman 中，向 ES 服务器发 POST 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/shopping/_doc">http://127.0.0.1:9200/shopping/_doc</a></p>
<p>请求体内容为：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br> <span class="hljs-attr">&quot;title&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;小米手机&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;category&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;小米&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;images&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;http://www.gulixueyuan.com/xm.jpg&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;price&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-number">3999.00</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p><img src="/blog/ElasticSearch.assets/image-20220808134645623.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808134645623"></p>
<p>此处发送请求的方式必须为POST，不能时PUT，否则会发生错误</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808134827920.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808134827920"></p>
<p>服务器响应结果如下：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808134850772.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808134850772"></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-string">&quot;_index&quot;</span>【索引】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;shopping&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;_type&quot;</span>【类型-文档】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;_doc&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;_id&quot;</span>【唯一标识】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;7s__e4IBCAQrMMvidOjT&quot;</span><span class="hljs-punctuation">,</span> #可以类比为MySQL中的主键，随机生成<br>    <span class="hljs-string">&quot;_version&quot;</span>【版本】<span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;result&quot;</span>【结果】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;created&quot;</span><span class="hljs-punctuation">,</span> #这里的create表示创建成果<br>    <span class="hljs-string">&quot;_shards&quot;</span>【分片】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-string">&quot;total&quot;</span>【分片-总数】<span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-string">&quot;successful&quot;</span>【分片-成功】<span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-string">&quot;failed&quot;</span>【分片-失败】<span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br>    <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_seq_no&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_primary_term&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p>上面的数据创建后，由于没有指定数据唯一性标识（ID），默认情况下，ES 服务器会随机 生成一个。</p>
<p>如果想要自定义唯一性标识，需要在创建时指定：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/shopping/_doc/1">http://127.0.0.1:9200/shopping/_doc/1</a></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808135250463.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808135250463"></p>
<p><strong>$\textcolor{red}{此处需要注意，如果增加数据时明确数据主键，那么请求方式也可以为PUT}$</strong></p>
<h6 id="2-查看文档"><a href="#2-查看文档" class="headerlink" title="2.查看文档"></a>2.查看文档</h6><p>查看文档时，需要指明文档的唯一性标识，类似于 MySQL 中数据的主键查询 在 Postman 中，向 ES 服务器发 GET 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/shopping/_doc/1">http://127.0.0.1:9200/shopping/_doc/1</a></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808135510629.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808135510629"></p>
<p>查询成功后，服务器响应结果</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808135549068.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808135549068"></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-string">&quot;_index&quot;</span>【索引】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;shopping&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;_type&quot;</span>【类型-文档】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;_doc&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_id&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_version&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_seq_no&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_primary_term&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;found&quot;</span>【查看结果】<span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span> #<span class="hljs-literal"><span class="hljs-keyword">true</span></span>表示查找到，<span class="hljs-literal"><span class="hljs-keyword">false</span></span>表示未找到<br>    <span class="hljs-string">&quot;_source&quot;</span>【文档源信息】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-attr">&quot;title&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;小米手机&quot;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;category&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;小米&quot;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;images&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;http://www.gulixueyuan.com/xm.jpg&quot;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;price&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3999.00</span><br>    <span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h6 id="3-修改文档"><a href="#3-修改文档" class="headerlink" title="3.修改文档"></a>3.修改文档</h6><p>和新增文档一样，输入相同的 URL 地址请求，如果请求体变化，会将原有的数据内容覆盖 在 Postman 中，向 ES 服务器发 POST 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/shopping/_doc/1">http://127.0.0.1:9200/shopping/_doc/1</a> </p>
<p>请求体内容为:</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br> <span class="hljs-attr">&quot;title&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;华为手机&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;category&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;华为&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;images&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;http://www.gulixueyuan.com/hw.jpg&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;price&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-number">4999.00</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p><img src="/blog/ElasticSearch.assets/image-20220808140250362.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808140250362"></p>
<p>修改成功后，服务器响应结果</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808140321449.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808140321449"></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;_index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;shopping&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;_doc&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_id&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_version&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;result&quot;</span>【结果】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;updated&quot;</span><span class="hljs-punctuation">,</span>  #updated表示数据被更新<br>    <span class="hljs-attr">&quot;_shards&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-attr">&quot;total&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;successful&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;failed&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br>    <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_seq_no&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_primary_term&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h6 id="4-修改字段"><a href="#4-修改字段" class="headerlink" title="4.修改字段"></a>4.修改字段</h6><p>修改数据时，也可以只修改某一给条数据的局部信息</p>
<p>在 Postman 中，向 ES 服务器发 POST 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/shopping/_update/1">http://127.0.0.1:9200/shopping/_update/1</a> 请求体内容为：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span> <br> 	<span class="hljs-attr">&quot;doc&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br> 		<span class="hljs-attr">&quot;price&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-number">3000.00</span><br> 	<span class="hljs-punctuation">&#125;</span> <br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p><img src="/blog/ElasticSearch.assets/image-20220808140722706.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808140722706"></p>
<p>修改成功后，服务器返回结果</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808140738955.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808140738955"></p>
<p>根据唯一标识，查询文档数据，文档数据已更新</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808140826389.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808140826389"></p>
<h6 id="5-删除文档"><a href="#5-删除文档" class="headerlink" title="5.删除文档"></a>5.删除文档</h6><p>删除一个文档不会立即从磁盘上移除，它只是被标记成已删除（逻辑删除）。 在 Postman 中，向 ES 服务器发 DELETE 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/shopping/_doc/1">http://127.0.0.1:9200/shopping/_doc/1</a></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808140951166.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808140951166"></p>
<p>删除成功，服务器响应结果：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808141003045.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808141003045"></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;_index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;shopping&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;_doc&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_id&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;_version&quot;</span>【版本】<span class="hljs-punctuation">:</span> <span class="hljs-number">4</span><span class="hljs-punctuation">,</span> #对数据的操作，都会更新版本<br>    <span class="hljs-string">&quot;result&quot;</span>【结果】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;deleted&quot;</span><span class="hljs-punctuation">,</span> #deleted表示数据被标记为删除<br>    <span class="hljs-attr">&quot;_shards&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-attr">&quot;total&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;successful&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;failed&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br>    <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_seq_no&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_primary_term&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p>删除后再查询当前文档信息</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808141200941.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808141200941"></p>
<p>如果删除一个并不存在的文档</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808141302619.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808141302619"></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;_index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;shopping&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;_doc&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_id&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_version&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;result&quot;</span>【结果】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;not_found&quot;</span><span class="hljs-punctuation">,</span> #表示未查找到<br>    <span class="hljs-attr">&quot;_shards&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-attr">&quot;total&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;successful&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;failed&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br>    <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_seq_no&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_primary_term&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h6 id="6-条件删除文档"><a href="#6-条件删除文档" class="headerlink" title="6.条件删除文档"></a>6.条件删除文档</h6><p>一般删除数据都是根据文档的唯一性标识进行删除，实际操作时，也可以根据条件对多条数 据进行删除</p>
<p>首先分别增加多条数据:</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br> <span class="hljs-attr">&quot;title&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;小米手机&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;category&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;小米&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;images&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;http://www.gulixueyuan.com/xm.jpg&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;price&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-number">4000.00</span><br><span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#123;</span><br> <span class="hljs-attr">&quot;title&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;华为手机&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;category&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;华为&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;images&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;http://www.gulixueyuan.com/hw.jpg&quot;</span><span class="hljs-punctuation">,</span><br> <span class="hljs-attr">&quot;price&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-number">4000.00</span><br><span class="hljs-punctuation">&#125;</span><br><br></code></pre></td></tr></table></figure>

<p><img src="/blog/ElasticSearch.assets/image-20220808141507821.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808141507821"></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808141708015.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808141708015"></p>
<p>向 ES 服务器发 POST 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/shopping/_delete_by_query">http://127.0.0.1:9200/shopping/_delete_by_query</a></p>
<p>请求体内容为：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br> 	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-punctuation">&#123;</span><br> 		<span class="hljs-attr">&quot;match&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-punctuation">&#123;</span><br> 			<span class="hljs-attr">&quot;price&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-number">4000.00</span><br> 		 <span class="hljs-punctuation">&#125;</span><br> 	 <span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p><img src="/blog/ElasticSearch.assets/image-20220808142250522.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808142250522"></p>
<p>删除成功后，服务器响应结果：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808143016518.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808143016518"></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-string">&quot;took&quot;</span>【耗时】<span class="hljs-punctuation">:</span> <span class="hljs-number">84</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;timed_out&quot;</span>【是否超时】<span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;total&quot;</span>【总数】<span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;deleted&quot;</span>【删除数量】<span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;batches&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;version_conflicts&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;noops&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;retries&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-attr">&quot;bulk&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;search&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br>    <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;throttled_millis&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;requests_per_second&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">-1.0</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;throttled_until_millis&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;failures&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-punctuation">]</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h5 id="2-2-4-3-映射操作"><a href="#2-2-4-3-映射操作" class="headerlink" title="2.2.4.3 映射操作"></a>2.2.4.3 映射操作</h5><p>​		有了索引库，等于有了数据库中的 database。</p>
<p>​		接下来就需要建索引库(index)中的映射了，**类似于数据库(database)中的表结构(table)**。 创建数据库表需要设置字段名称，类型，长度，约束等；索引库也一样，需要知道这个类型 下有哪些字段，每个字段有哪些约束信息，这就叫做映射(mapping)。</p>
<h6 id="1-创建映射"><a href="#1-创建映射" class="headerlink" title="1.创建映射"></a>1.创建映射</h6><p>在 Postman 中，向 ES 服务器发 PUT 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/student/_mapping">http://127.0.0.1:9200/student/_mapping</a> </p>
<p>请求体内容为：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;properties&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;text&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><br>		<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;text&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><br>		<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;long&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p><img src="/blog/ElasticSearch.assets/image-20220808143624645.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808143624645"></p>
<p>服务器响应结果如下：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808143556487.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808143556487"></p>
<p>映射数据说明：</p>
<ul>
<li><p>字段名：任意填写，下卖弄指定许多属性，例如：title，subtitle，images，price</p>
</li>
<li><p>type：类型，ElasticSearch中支持的数据类型非常丰富，说几个关键的</p>
<ul>
<li><p>String类型，又分两种</p>
<p>text：可分词</p>
<p>keyword：不可分词，数据会作为完整字段进行匹配</p>
</li>
<li><p>Numerical：数值类型，分两种</p>
<p>基本数据类型：long、integer、short、byte、double、float、half_float</p>
<p>浮点数的高精度类型：scaled_float3</p>
</li>
<li><p>Date：日期类型</p>
</li>
<li><p>Array：数据类型</p>
</li>
<li><p>Object：对象</p>
</li>
</ul>
</li>
<li><p>index：是否索引，默认为true，也就是说你不进行任何配置，所有字段都会被索引。</p>
<ul>
<li>true：字段会被索引，则可以用来进行搜索</li>
<li>false：字段不会被索引，不能用来搜索</li>
</ul>
</li>
<li><p>store：是否将数据进行独立存储，，默认为false</p>
<p>原始的文本会存储在_source里面，默认情况下其他提取出来的字段都不是独立存储的，而是从source里面提取出来的。当然你也可以独立的存储某个字段，只要设置 “store”: true 即可，获取独立存储的字段要比从source 中解析快得多，但是也会占用 更多的空间，所以要根据实际业务需求来设置。</p>
</li>
<li><p>analyzer：分词器，这里的ik_max_word即使用ik分词器</p>
</li>
</ul>
<h6 id="2-查看映射"><a href="#2-查看映射" class="headerlink" title="2.查看映射"></a>2.查看映射</h6><p>在 Postman 中，向 ES 服务器发 GET 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/student/_mapping">http://127.0.0.1:9200/student/_mapping</a></p>
<p><img src="/blog/ElasticSearch.assets/image-20220808144714673.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808144714673"></p>
<p>服务器响应结果如下：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808144730830.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808144730830"></p>
<h6 id="3-索引映射关联"><a href="#3-索引映射关联" class="headerlink" title="3. 索引映射关联"></a>3. 索引映射关联</h6><p>在 Postman 中，向 ES 服务器发 PUT 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/student1">http://127.0.0.1:9200/student1</a></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;settings&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;mappings&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;properties&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;text&quot;</span><span class="hljs-punctuation">,</span><br>				<span class="hljs-attr">&quot;index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><br>			<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;text&quot;</span><span class="hljs-punctuation">,</span><br>				<span class="hljs-attr">&quot;index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><br>			<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;long&quot;</span><span class="hljs-punctuation">,</span><br>				<span class="hljs-attr">&quot;index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p><img src="/blog/ElasticSearch.assets/image-20220808145016470.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808145016470"></p>
<p>服务器响应结果如下：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808145040976.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808145040976"></p>
<h5 id="2-2-4-4-高级查询"><a href="#2-2-4-4-高级查询" class="headerlink" title="2.2.4.4 高级查询"></a>2.2.4.4 高级查询</h5><p>Elasticsearch 提供了基于 JSON 提供完整的查询 DSL 来定义查询 </p>
<p>以下所有查询均在postman中发送 GET 请求 ：<a target="_blank" rel="noopener" href="http://127.0.0.1:9200/student/_search">http://127.0.0.1:9200/student/_search</a></p>
<p>定义数据 :</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><code class="hljs json"># POST /student/_doc/<span class="hljs-number">1001</span><br><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;男&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">30</span><br><span class="hljs-punctuation">&#125;</span><br># POST /student/_doc/<span class="hljs-number">1002</span><br><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;lisi&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;lisi&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;男&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">20</span><br><span class="hljs-punctuation">&#125;</span><br># POST /student/_doc/<span class="hljs-number">1003</span><br><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;wangwu&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;wangwu&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;女&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">40</span><br><span class="hljs-punctuation">&#125;</span><br># POST /student/_doc/<span class="hljs-number">1004</span><br><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan1&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan1&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;女&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">50</span><br><span class="hljs-punctuation">&#125;</span><br># POST /student/_doc/<span class="hljs-number">1005</span><br><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan2&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan2&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;女&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">30</span><br><span class="hljs-punctuation">&#125;</span><br><br></code></pre></td></tr></table></figure>



<h6 id="1-查看所有文档"><a href="#1-查看所有文档" class="headerlink" title="1.查看所有文档"></a>1.查看所有文档</h6><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-attr">&quot;match_all&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-punctuation">&#123;</span><span class="hljs-punctuation">&#125;</span><br>    <span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br># <span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span>这里的query代表一个查询对象，里面可以有不同的查询属性<br># <span class="hljs-attr">&quot;match_all&quot;</span><span class="hljs-punctuation">:</span>查询类型，例如：match_all(代表查询所有)， match，term ， range 等等，<br># <span class="hljs-punctuation">&#123;</span>查询条件<span class="hljs-punctuation">&#125;</span>：查询条件会根据类型的不同，写法也有差异<br></code></pre></td></tr></table></figure>

<p><img src="/blog/ElasticSearch.assets/image-20220808150608283.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808150608283"></p>
<p>服务器响应结果如下：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;took&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">246</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;timed_out&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;_shards&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-attr">&quot;total&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;successful&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;skipped&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;failed&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br>    <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;hits&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-attr">&quot;total&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>            <span class="hljs-attr">&quot;value&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;relation&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;eq&quot;</span><br>        <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;max_score&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1.0</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;hits&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>            <span class="hljs-punctuation">&#123;</span><br>                <span class="hljs-attr">&quot;_index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;student&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;_doc&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_id&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1001&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_score&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1.0</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_source&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>                    <span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;男&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">30</span><br>                <span class="hljs-punctuation">&#125;</span><br>            <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-punctuation">&#123;</span><br>                <span class="hljs-attr">&quot;_index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;student&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;_doc&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_id&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1002&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_score&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1.0</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_source&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>                    <span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;lisi&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;lisi&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;男&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">20</span><br>                <span class="hljs-punctuation">&#125;</span><br>            <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-punctuation">&#123;</span><br>                <span class="hljs-attr">&quot;_index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;student&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;_doc&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_id&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1003&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_score&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1.0</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_source&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>                    <span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;wangwu&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;wangwu&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;女&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">40</span><br>                <span class="hljs-punctuation">&#125;</span><br>            <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-punctuation">&#123;</span><br>                <span class="hljs-attr">&quot;_index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;student&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;_doc&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_id&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1004&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_score&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1.0</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_source&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>                    <span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan1&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan1&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;女&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">50</span><br>                <span class="hljs-punctuation">&#125;</span><br>            <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-punctuation">&#123;</span><br>                <span class="hljs-attr">&quot;_index&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;student&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;_doc&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_id&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;1005&quot;</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_score&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1.0</span><span class="hljs-punctuation">,</span><br>                <span class="hljs-attr">&quot;_source&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>                    <span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan2&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan2&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;女&quot;</span><span class="hljs-punctuation">,</span><br>                    <span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">30</span><br>                <span class="hljs-punctuation">&#125;</span><br>            <span class="hljs-punctuation">&#125;</span><br>        <span class="hljs-punctuation">]</span><br>    <span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-string">&quot;took&quot;</span>【查询总花费时间】<span class="hljs-punctuation">:</span> <span class="hljs-number">246</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;timed_out&quot;</span>【是否超时】<span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;_shards&quot;</span>【分片信息】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-string">&quot;total&quot;</span>【总数】<span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-string">&quot;successful&quot;</span>【成功】<span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-string">&quot;skipped&quot;</span>【忽略】<span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-string">&quot;failed&quot;</span>【失败】<span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br>    <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-string">&quot;hits&quot;</span>【搜索命中结果】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-string">&quot;total&quot;</span>【搜索条件匹配的文档总数】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>            <span class="hljs-string">&quot;value&quot;</span>【总命中计数的值】<span class="hljs-punctuation">:</span> <span class="hljs-number">5</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-string">&quot;relation&quot;</span>【计数规则】<span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;eq&quot;</span>  #eq表示计数准确，get表示计数不准确<br>        <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-string">&quot;max_score&quot;</span>【匹配值分值】<span class="hljs-punctuation">:</span> <span class="hljs-number">1.0</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-string">&quot;hits&quot;</span>【命中结果集合】<span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>           ....<br>        <span class="hljs-punctuation">]</span><br>    <span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>



<h6 id="2-匹配查询"><a href="#2-匹配查询" class="headerlink" title="2.匹配查询"></a>2.匹配查询</h6><p>match 匹配类型查询，会把查询条件进行分词，然后进行查询，多个词条之间是 or 的关系 </p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br> <span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;match&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;zhangsan&quot;</span><br>    <span class="hljs-punctuation">&#125;</span><br>  <span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>





<p><img src="/blog/ElasticSearch.assets/image-20220808151458172.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808151458172"></p>
<h6 id="3-字段匹配查询"><a href="#3-字段匹配查询" class="headerlink" title="3.字段匹配查询"></a>3.字段匹配查询</h6><p>multi_match 与 match 类似，不同的是它可以在多个字段中查询。 </p>
<figure class="highlight prolog"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs prolog">&#123;<br>    <span class="hljs-string">&quot;query&quot;</span>: &#123;<br>        <span class="hljs-string">&quot;multi_match&quot;</span>: &#123;<br>            <span class="hljs-string">&quot;query&quot;</span>: <span class="hljs-string">&quot;zhangsan&quot;</span>,<br>            <span class="hljs-string">&quot;fields&quot;</span>: [<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;nickname&quot;</span>]<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<h6 id="4-关键字精确查询"><a href="#4-关键字精确查询" class="headerlink" title="4.关键字精确查询"></a>4.关键字精确查询</h6><p>term 查询，精确的关键词匹配查询，不对查询条件进行分词。</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;term&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;value&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h6 id="5-多关键字精确查询"><a href="#5-多关键字精确查询" class="headerlink" title="5. 多关键字精确查询"></a>5. 多关键字精确查询</h6><p>terms 查询和 term 查询一样，但它允许你指定多值进行匹配。 如果这个字段包含了指定值中的任何一个值，那么这个文档满足条件，类似于 mysql 的 in</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;terms&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>				<span class="hljs-string">&quot;zhangsan&quot;</span><span class="hljs-punctuation">,</span><br>				<span class="hljs-string">&quot;lisi&quot;</span><br>			<span class="hljs-punctuation">]</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h6 id="6-指定查询字段"><a href="#6-指定查询字段" class="headerlink" title="6. 指定查询字段"></a>6. 指定查询字段</h6><p>默认情况下，Elasticsearch 在搜索的结果中，会把文档中保存在source 的所有字段都返回。 如果我们只想获取其中的部分字段，我们可以添加source 的过滤</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;_source&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>		<span class="hljs-string">&quot;name&quot;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-string">&quot;nickname&quot;</span><br>	<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;terms&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>				<span class="hljs-string">&quot;zhangsan&quot;</span><br>			<span class="hljs-punctuation">]</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h6 id="7-过滤字段"><a href="#7-过滤字段" class="headerlink" title="7.过滤字段"></a>7.过滤字段</h6><p>我们也可以通过：</p>
<ul>
<li>includes：来指定想要显示的字段</li>
<li>excludes：来指定不想要显示的字段</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;_source&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;includes&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>			<span class="hljs-string">&quot;name&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-string">&quot;nickname&quot;</span><br>		<span class="hljs-punctuation">]</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;terms&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;nickname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>				<span class="hljs-string">&quot;zhangsan&quot;</span><br>			<span class="hljs-punctuation">]</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h6 id="8-组合查询"><a href="#8-组合查询" class="headerlink" title="8.组合查询"></a>8.组合查询</h6><p><code>bool</code>把各种其它查询通过<code>must</code>（必须 ）、<code>must_not</code>（必须不）、<code>should</code>（应该）的方 式进行组合</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;bool&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;must&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>				<span class="hljs-punctuation">&#123;</span><br>					<span class="hljs-attr">&quot;match&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>						<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan&quot;</span><br>					<span class="hljs-punctuation">&#125;</span><br>				<span class="hljs-punctuation">&#125;</span><br>			<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;must_not&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>				<span class="hljs-punctuation">&#123;</span><br>					<span class="hljs-attr">&quot;match&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>						<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;40&quot;</span><br>					<span class="hljs-punctuation">&#125;</span><br>				<span class="hljs-punctuation">&#125;</span><br>			<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;should&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>				<span class="hljs-punctuation">&#123;</span><br>					<span class="hljs-attr">&quot;match&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>						<span class="hljs-attr">&quot;sex&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;男&quot;</span><br>					<span class="hljs-punctuation">&#125;</span><br>				<span class="hljs-punctuation">&#125;</span><br>			<span class="hljs-punctuation">]</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>



<h6 id="9-范围查询"><a href="#9-范围查询" class="headerlink" title="9.范围查询"></a>9.范围查询</h6><p>range 查询找出那些落在指定区间的数字或者事件。range查询允许以下字符</p>
<table>
<thead>
<tr>
<th align="center">操作符</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">gt</td>
<td align="center">大于 &gt;</td>
</tr>
<tr>
<td align="center">gte</td>
<td align="center">大于等于 &gt;&#x3D;</td>
</tr>
<tr>
<td align="center">lt</td>
<td align="center">小于 &lt;</td>
</tr>
<tr>
<td align="center">lte</td>
<td align="center">小于等于 &lt;&#x3D;</td>
</tr>
</tbody></table>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;range&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;gte&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">30</span><span class="hljs-punctuation">,</span><br>				<span class="hljs-attr">&quot;lte&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">35</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>



<h6 id="10-模糊查询"><a href="#10-模糊查询" class="headerlink" title="10.模糊查询"></a>10.模糊查询</h6><p>返回包含与搜索字词相似的字词的文档。 编辑距离是将一个术语转换为另一个术语所需的一个字符更改的次数。这些更改可以包括：</p>
<ul>
<li>更改字符（box → fox）</li>
<li>删除字符（black → lack）</li>
<li>插入字符（sic → sick）</li>
<li>转置两个相邻字符（act → cat）</li>
</ul>
<p>为了找到相似的术语，fuzzy 查询会在指定的编辑距离内创建一组搜索词的所有可能的变体 或扩展。然后查询返回每个扩展的完全匹配。</p>
<p>通过 fuzziness 修改编辑距离。一般使用默认值 AUTO，根据术语的长度生成编辑距离。</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;fuzzy&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;title&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;value&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;fuzzy&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;title&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;value&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan&quot;</span><span class="hljs-punctuation">,</span><br>				<span class="hljs-attr">&quot;fuzziness&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span>  #表示可以模糊差别两个字符<br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>



<h6 id="11-单字段排序"><a href="#11-单字段排序" class="headerlink" title="11.单字段排序"></a>11.单字段排序</h6><p>sort 可以让我们按照不同的字段进行排序，并且通过 order 指定排序的方式。desc 降序，asc 升序。</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;match&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan&quot;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;sort&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;order&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;desc&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">]</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>



<p>12.多字段排序</p>
<p>假定我们想要结合使用 age 和 _score 进行查询，并且匹配的结果首先按照年龄排序，然后按照相关性得分排序</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;match_all&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;sort&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;order&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;desc&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;_score&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;order&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;desc&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">]</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>



<h6 id="13-高亮查询"><a href="#13-高亮查询" class="headerlink" title="13.高亮查询"></a>13.高亮查询</h6><p>在进行关键字搜索时，搜索出的内容中的关键字会显示不同的颜色，称之为高亮</p>
<blockquote>
<p>在百度搜索”京东</p>
</blockquote>
<p><img src="/blog/ElasticSearch.assets/image-20220808155846815.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808155846815"></p>
<p>Elasticsearch 可以对查询内容中的关键字部分，进行标签和样式(高亮)的设置。 在使用 match 查询的同时，加上一个 highlight 属性：</p>
<ul>
<li>pre_tags：前置标签</li>
<li>post_tags：后置标签 </li>
<li>fields：需要高亮的字段</li>
<li>title：这里声明 title 字段需要高亮，后面可以为这个字段设置特有配置，也可以空</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;match&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;zhangsan&quot;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;highlight&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;pre_tags&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;font color=&#x27;red&#x27;&gt;&quot;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-attr">&quot;post_tags&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;/font&gt;&quot;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-attr">&quot;fields&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>



<h6 id="14-分页查询"><a href="#14-分页查询" class="headerlink" title="14.分页查询"></a>14.分页查询</h6><p>from：当前页的起始索引，默认从 0 开始。 from &#x3D; (pageNum - 1) * size size：每页显示多少条</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;query&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;match_all&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;sort&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;order&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;desc&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;from&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;size&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>



<h6 id="15-聚合查询"><a href="#15-聚合查询" class="headerlink" title="15. 聚合查询"></a>15. 聚合查询</h6><p>聚合允许使用者对 es 文档进行统计分析，类似与关系型数据库中的 group by，当然还有很 多其他的聚合，例如取最大值、平均值等等。</p>
<ul>
<li>对某个字段取最大值 max</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;aggs&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;max_age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;max&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;field&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;age&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;size&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<ul>
<li>对某个字段取最小值 min</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;aggs&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;min_age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;min&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;field&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;age&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;size&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<ul>
<li>对某个字段求和 sum</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;aggs&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;sum_age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;sum&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;field&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;age&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;size&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<ul>
<li>对某个字段取平均值 avg</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;aggs&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;avg_age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;avg&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;field&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;age&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;size&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<ul>
<li>对某个字段的值进行去重之后再取总数</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;aggs&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;distinct_age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;cardinality&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;field&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;age&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;size&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<ul>
<li>State 聚合</li>
</ul>
<p>stats 聚合，对某个字段一次性返回 <strong>count，max，min，avg 和 sum</strong> 五个指标</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;aggs&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;stats_age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;stats&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;field&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;age&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;size&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>



<h6 id="16-桶聚合查询"><a href="#16-桶聚合查询" class="headerlink" title="16.桶聚合查询"></a>16.桶聚合查询</h6><p>桶聚和相当于 sql 中的 group by 语句</p>
<ul>
<li>terms 聚合，分组统计</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;aggs&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;age_groupby&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;terms&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;field&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;age&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;size&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<ul>
<li>在 terms 分组下再进行聚合</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;aggs&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;age_groupby&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;terms&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;field&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;age&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;size&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>



<h4 id="2-2-5-Java-API-操作"><a href="#2-2-5-Java-API-操作" class="headerlink" title="2.2.5 Java API 操作"></a>2.2.5 Java API 操作</h4><p>​		Elasticsearch 软件是由 Java 语言开发的，所以也可以通过 Java API 的方式对 Elasticsearch 服务进行访问</p>
<h5 id="2-2-5-1-创建-Maven-项目"><a href="#2-2-5-1-创建-Maven-项目" class="headerlink" title="2.2.5.1 创建 Maven 项目"></a>2.2.5.1 创建 Maven 项目</h5><p>​		在IDEA工具中创建一个maven项目，并修改pom文件，增加Maven依赖关系</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.elasticsearch<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>elasticsearch<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>7.8.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-comment">&lt;!-- elasticsearch 的客户端 --&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.elasticsearch.client<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>elasticsearch-rest-high-level-client<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>7.8.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-comment">&lt;!-- elasticsearch 依赖 2.x 的 log4j --&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.apache.logging.log4j<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>log4j-api<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.8.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.apache.logging.log4j<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>log4j-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.8.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.fasterxml.jackson.core<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>jackson-databind<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.9.9<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-comment">&lt;!-- junit 单元测试 --&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>4.12<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span><br></code></pre></td></tr></table></figure>



<h5 id="2-2-5-2-客户端对象"><a href="#2-2-5-2-客户端对象" class="headerlink" title="2.2.5.2 客户端对象"></a>2.2.5.2 客户端对象</h5><p>​		创建 Elasticsearch01_Client 类，代码中创建 Elasticsearch 客户端对象 因为早期版本的客户端对象已经不再推荐使用，且在未来版本中会被删除，所以这里我们采 用高级 REST 客户端对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ESTest_Client</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>        <span class="hljs-comment">//创建ES客户端</span><br>        <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">esClient</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>                RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>        <span class="hljs-comment">//关闭客户端连接</span><br>        esClient.close();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>$\textcolor{red}{注意}$<strong>：</strong>9200</strong> 端口为 Elasticsearch 的 Web 通信端口，<strong>localhost</strong> 为启动 ES 服务的主机名执行代码，查看控制台信息：如果运行成功没有报错并自动退出，则成功</p>
<h5 id="2-2-5-3-索引操作"><a href="#2-2-5-3-索引操作" class="headerlink" title="2.2.5.3 索引操作"></a>2.2.5.3 索引操作</h5><p>​		ES 服务器正常启动后，可以通过 Java API 客户端对象对 ES 索引进行操作</p>
<h6 id="1-创建索引-1"><a href="#1-创建索引-1" class="headerlink" title="1.创建索引"></a>1.创建索引</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ESTest_Index_Create</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>        <span class="hljs-comment">//创建ES客户端</span><br>        <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">esClient</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>                RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>        <span class="hljs-comment">//创建索引 - 请求对象</span><br>        <span class="hljs-type">CreateIndexRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">CreateIndexRequest</span>(<span class="hljs-string">&quot;users&quot;</span>);<br>        <span class="hljs-comment">//发送请求，获取响应</span><br>        <span class="hljs-type">CreateIndexResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> esClient.indices().create(request, RequestOptions.DEFAULT);<br>        <span class="hljs-comment">//获取结果</span><br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">acknowledged</span> <span class="hljs-operator">=</span> response.isAcknowledged();<br><br>        System.out.println(<span class="hljs-string">&quot;操作状态：&quot;</span>+acknowledged);<br>        <span class="hljs-comment">//关闭客户端连接</span><br>        esClient.close();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>操作结果：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808162410184.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808162410184"></p>
<h6 id="2-查看索引"><a href="#2-查看索引" class="headerlink" title="2.查看索引"></a>2.查看索引</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ESTest_Index_Search</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>        <span class="hljs-comment">//创建ES客户端</span><br>        <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>                RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>        <span class="hljs-comment">//查询索引 - 请求对象</span><br>        <span class="hljs-type">GetIndexRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">GetIndexRequest</span>(<span class="hljs-string">&quot;users&quot;</span>);<br>        <span class="hljs-comment">//发送请求，获取响应</span><br>        <span class="hljs-type">GetIndexResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.indices().get(request, RequestOptions.DEFAULT);<br><br>        System.out.println(<span class="hljs-string">&quot;aliases：&quot;</span>+response.getAliases());<br>        System.out.println(<span class="hljs-string">&quot;mappings：&quot;</span>+response.getMappings());<br>        System.out.println(<span class="hljs-string">&quot;settings：&quot;</span>+response.getSettings());<br>        <span class="hljs-comment">//关闭客户端连接</span><br>        client.close();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>操作结果：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808162521591.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808162521591"></p>
<h6 id="3-删除索引"><a href="#3-删除索引" class="headerlink" title="3.删除索引"></a>3.删除索引</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ESTest_Index_Delete</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>        <span class="hljs-comment">//创建ES客户端</span><br>        <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>                RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>        <span class="hljs-comment">//删除索引 - 请求对象</span><br>        <span class="hljs-type">DeleteIndexRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">DeleteIndexRequest</span>(<span class="hljs-string">&quot;user&quot;</span>);<br>        <span class="hljs-comment">//发送请求，获取响应</span><br>        <span class="hljs-type">AcknowledgedResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.indices().delete(request, RequestOptions.DEFAULT);<br><br>        System.out.println(<span class="hljs-string">&quot;操作结果：&quot;</span>+response.isAcknowledged());<br>        <span class="hljs-comment">//关闭客户端连接</span><br>        client.close();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>操作结果：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808162629493.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808162629493"></p>
<h5 id="2-2-5-4-文档操作"><a href="#2-2-5-4-文档操作" class="headerlink" title="2.2.5.4 文档操作"></a>2.2.5.4 文档操作</h5><h6 id="1-新增文档"><a href="#1-新增文档" class="headerlink" title="1.新增文档"></a>1.新增文档</h6><p>创建数据模型</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.vincent;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span> &#123;<br>    <span class="hljs-keyword">private</span> String name;<br>    <span class="hljs-keyword">private</span> Integer age;<br>    <span class="hljs-keyword">private</span> String sex;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">User</span><span class="hljs-params">()</span> &#123;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">User</span><span class="hljs-params">(String name, Integer age, String sex)</span> &#123;<br>        <span class="hljs-built_in">this</span>.name = name;<br>        <span class="hljs-built_in">this</span>.age = age;<br>        <span class="hljs-built_in">this</span>.sex = sex;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">getName</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> name;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setName</span><span class="hljs-params">(String name)</span> &#123;<br>        <span class="hljs-built_in">this</span>.name = name;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> Integer <span class="hljs-title function_">getAge</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> age;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setAge</span><span class="hljs-params">(Integer age)</span> &#123;<br>        <span class="hljs-built_in">this</span>.age = age;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">getSex</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> sex;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setSex</span><span class="hljs-params">(String sex)</span> &#123;<br>        <span class="hljs-built_in">this</span>.sex = sex;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">toString</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;User&#123;&quot;</span> +<br>                <span class="hljs-string">&quot;name=&#x27;&quot;</span> + name + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +<br>                <span class="hljs-string">&quot;, age=&quot;</span> + age +<br>                <span class="hljs-string">&quot;, sex=&#x27;&quot;</span> + sex + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +<br>                <span class="hljs-string">&#x27;&#125;&#x27;</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>创建数据，添加到文档中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ESTest_Doc_Insert</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>        <span class="hljs-comment">//创建ES客户端</span><br>        <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>                RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>        <span class="hljs-comment">//插入文档</span><br>        <span class="hljs-type">IndexRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">IndexRequest</span>();<br>        <span class="hljs-comment">//设置索引及唯一标识</span><br>        request.index(<span class="hljs-string">&quot;users&quot;</span>).id(<span class="hljs-string">&quot;1001&quot;</span>);<br>        <span class="hljs-comment">//创建数据对象</span><br>        <span class="hljs-type">User</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">User</span>();<br>        user.setName(<span class="hljs-string">&quot;zhangsan&quot;</span>);<br>        user.setAge(<span class="hljs-number">30</span>);<br>        user.setSex(<span class="hljs-string">&quot;男&quot;</span>);<br><br>        <span class="hljs-type">ObjectMapper</span> <span class="hljs-variable">objectMapper</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ObjectMapper</span>();<br>        <span class="hljs-type">String</span> <span class="hljs-variable">userJson</span> <span class="hljs-operator">=</span> objectMapper.writeValueAsString(user);<br><br>        <span class="hljs-comment">//添加文档数据，数据格式为Json格式</span><br>        request.source(userJson, XContentType.JSON);<br><br>        <span class="hljs-comment">//客户端发送请求，获取响应对象</span><br>        <span class="hljs-type">IndexResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.index(request, RequestOptions.DEFAULT);<br>        System.out.println(response.getResult());<br>        <span class="hljs-comment">//关闭客户端连接</span><br>        client.close();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>操作结果：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808162845632.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808162845632"></p>
<h6 id="2-修改文档"><a href="#2-修改文档" class="headerlink" title="2.修改文档"></a>2.修改文档</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ESTest_Doc_Update</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>        <span class="hljs-comment">//创建ES客户端</span><br>        <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>                RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>        <span class="hljs-comment">//修改文档</span><br>        <span class="hljs-type">UpdateRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">UpdateRequest</span>();<br>        <span class="hljs-comment">//设置索引及唯一标识</span><br>        request.index(<span class="hljs-string">&quot;users&quot;</span>).id(<span class="hljs-string">&quot;1001&quot;</span>);<br>        <span class="hljs-comment">//设置请求体，对数据进行修改</span><br>        request.doc(XContentType.JSON,<span class="hljs-string">&quot;sex&quot;</span>,<span class="hljs-string">&quot;女&quot;</span>);<br><br>        <span class="hljs-comment">//客户端发送请求，获取响应对象</span><br>        <span class="hljs-type">UpdateResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.update(request, RequestOptions.DEFAULT);<br>        System.out.println(response.getResult());<br>        <span class="hljs-comment">//关闭客户端连接</span><br>        client.close();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>操作结果：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808162943194.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808162943194"></p>
<h6 id="3-查询文档"><a href="#3-查询文档" class="headerlink" title="3.查询文档"></a>3.查询文档</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ESTest_Doc_Get</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>        <span class="hljs-comment">//创建ES客户端</span><br>        <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>                RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>        <span class="hljs-type">GetRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">GetRequest</span>();<br>        request.index(<span class="hljs-string">&quot;user&quot;</span>).id(<span class="hljs-string">&quot;1001&quot;</span>);<br>        GetResponse response= client.get(request, RequestOptions.DEFAULT);<br>        System.out.println(response.getSourceAsString());<br>        <span class="hljs-comment">//关闭客户端连接</span><br>        client.close();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>操作结果：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808163123026.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808163123026"></p>
<h6 id="4-删除文档"><a href="#4-删除文档" class="headerlink" title="4.删除文档"></a>4.删除文档</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ESTest_Doc_Delete</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>        <span class="hljs-comment">//创建ES客户端</span><br>        <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>                RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>        <span class="hljs-type">DeleteRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">DeleteRequest</span>();<br>        request.index(<span class="hljs-string">&quot;users&quot;</span>).id(<span class="hljs-string">&quot;1001&quot;</span>);<br>        <span class="hljs-type">DeleteResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.delete(request, RequestOptions.DEFAULT);<br>        System.out.println(response.toString());<br>        <span class="hljs-comment">//关闭客户端连接</span><br>        client.close();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>操作结果：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808163216684.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808163216684"></p>
<h6 id="5-批量操作"><a href="#5-批量操作" class="headerlink" title="5.批量操作"></a>5.批量操作</h6><ul>
<li>批量新增</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ESTest_Doc_Insert_batch</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>        <span class="hljs-comment">//创建ES客户端</span><br>        <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>                RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>        <span class="hljs-comment">//批量插入文档</span><br>        <span class="hljs-type">BulkRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">BulkRequest</span>();<br>        request.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">IndexRequest</span>().index(<span class="hljs-string">&quot;user&quot;</span>).id(<span class="hljs-string">&quot;1001&quot;</span>).source(XContentType.JSON,<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;zhangsan&quot;</span>,<span class="hljs-string">&quot;age&quot;</span>,<span class="hljs-number">30</span>,<span class="hljs-string">&quot;sex&quot;</span>,<span class="hljs-string">&quot;男&quot;</span>));<br>        request.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">IndexRequest</span>().index(<span class="hljs-string">&quot;user&quot;</span>).id(<span class="hljs-string">&quot;1002&quot;</span>).source(XContentType.JSON,<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;lisi&quot;</span>,<span class="hljs-string">&quot;age&quot;</span>,<span class="hljs-number">40</span>,<span class="hljs-string">&quot;sex&quot;</span>,<span class="hljs-string">&quot;男&quot;</span>));<br>        request.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">IndexRequest</span>().index(<span class="hljs-string">&quot;user&quot;</span>).id(<span class="hljs-string">&quot;1003&quot;</span>).source(XContentType.JSON,<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;wangwu&quot;</span>,<span class="hljs-string">&quot;age&quot;</span>,<span class="hljs-number">30</span>,<span class="hljs-string">&quot;sex&quot;</span>,<span class="hljs-string">&quot;男&quot;</span>));<br>        request.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">IndexRequest</span>().index(<span class="hljs-string">&quot;user&quot;</span>).id(<span class="hljs-string">&quot;1004&quot;</span>).source(XContentType.JSON,<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;wangwu1&quot;</span>,<span class="hljs-string">&quot;age&quot;</span>,<span class="hljs-number">30</span>,<span class="hljs-string">&quot;sex&quot;</span>,<span class="hljs-string">&quot;女&quot;</span>));<br>        request.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">IndexRequest</span>().index(<span class="hljs-string">&quot;user&quot;</span>).id(<span class="hljs-string">&quot;1005&quot;</span>).source(XContentType.JSON,<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;wangwu2&quot;</span>,<span class="hljs-string">&quot;age&quot;</span>,<span class="hljs-number">40</span>,<span class="hljs-string">&quot;sex&quot;</span>,<span class="hljs-string">&quot;女&quot;</span>));<br>        request.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">IndexRequest</span>().index(<span class="hljs-string">&quot;user&quot;</span>).id(<span class="hljs-string">&quot;1006&quot;</span>).source(XContentType.JSON,<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;wangwu3&quot;</span>,<span class="hljs-string">&quot;age&quot;</span>,<span class="hljs-number">50</span>,<span class="hljs-string">&quot;sex&quot;</span>,<span class="hljs-string">&quot;男&quot;</span>));<br>        <span class="hljs-type">BulkResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.bulk(request, RequestOptions.DEFAULT);<br>        System.out.println(response.getTook());<br>        <span class="hljs-comment">//关闭客户端连接</span><br>        client.close();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>操作结果：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808163358730.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808163358730"></p>
<ul>
<li>批量删除</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ESTest_Doc_Delete_batch</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>        <span class="hljs-comment">//创建ES客户端</span><br>        <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>                RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>        <span class="hljs-comment">//批量插入文档</span><br>        <span class="hljs-type">BulkRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">BulkRequest</span>();<br>        request.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">DeleteRequest</span>().index(<span class="hljs-string">&quot;user&quot;</span>).id(<span class="hljs-string">&quot;1001&quot;</span>));<br>        request.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">DeleteRequest</span>().index(<span class="hljs-string">&quot;user&quot;</span>).id(<span class="hljs-string">&quot;1002&quot;</span>));<br>        request.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">DeleteRequest</span>().index(<span class="hljs-string">&quot;user&quot;</span>).id(<span class="hljs-string">&quot;1003&quot;</span>));<br>        <span class="hljs-type">BulkResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.bulk(request, RequestOptions.DEFAULT);<br>        System.out.println(response.getTook());<br>        <span class="hljs-comment">//关闭客户端连接</span><br>        client.close();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<h5 id="2-2-5-5-高级查询"><a href="#2-2-5-5-高级查询" class="headerlink" title="2.2.5.5 高级查询"></a>2.2.5.5 高级查询</h5><h6 id="1-查询所有索引数据"><a href="#1-查询所有索引数据" class="headerlink" title="1.查询所有索引数据"></a>1.查询所有索引数据</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 1.全量查询</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">queryAll</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br>    <span class="hljs-comment">//创建ES客户端</span><br>    <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>            RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>    <span class="hljs-comment">//1.全量查询</span><br>    <span class="hljs-type">SearchRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchRequest</span>();<br>    request.indices(<span class="hljs-string">&quot;users&quot;</span>);<br>    <span class="hljs-comment">//构建SearchSourceBuilder</span><br>    <span class="hljs-type">SearchSourceBuilder</span> <span class="hljs-variable">sourceBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchSourceBuilder</span>();<br>    <span class="hljs-comment">//查询所有数据</span><br>    sourceBuilder.query(QueryBuilders.matchAllQuery());<br>    <span class="hljs-comment">//请求source</span><br>    request.source(sourceBuilder);<br>    <span class="hljs-type">SearchResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.search(request, RequestOptions.DEFAULT);<br><br>    <span class="hljs-comment">//获取所有hits</span><br>    <span class="hljs-type">SearchHits</span> <span class="hljs-variable">hits</span> <span class="hljs-operator">=</span> response.getHits();<br><br>    System.out.println(hits.getTotalHits());<br>    System.out.println(response.getTook());<br><br>    <span class="hljs-comment">//遍历输出hits</span><br>    <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>        System.out.println(hit.getSourceAsString());<br>    &#125;<br>    <span class="hljs-comment">//关闭客户端连接</span><br>    client.close();<br>&#125;<br></code></pre></td></tr></table></figure>

<h6 id="2-term-查询，查询条件为关键字"><a href="#2-term-查询，查询条件为关键字" class="headerlink" title="2.term 查询，查询条件为关键字"></a>2.term 查询，查询条件为关键字</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 2.条件查询</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">queryByCondition</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br><br>    <span class="hljs-comment">//创建ES客户端</span><br>    <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>            RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br>    <span class="hljs-comment">//2.条件查询</span><br>    <span class="hljs-type">SearchRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchRequest</span>();<br>    request.indices(<span class="hljs-string">&quot;user&quot;</span>);<br>    <span class="hljs-comment">//构建SearchSourceBuilder</span><br>    <span class="hljs-type">SearchSourceBuilder</span> <span class="hljs-variable">sourceBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchSourceBuilder</span>();<br><br>    sourceBuilder.query(QueryBuilders.termQuery(<span class="hljs-string">&quot;age&quot;</span>, <span class="hljs-number">30</span>));<br>    <span class="hljs-comment">//请求source</span><br>    request.source(sourceBuilder);<br>    <span class="hljs-type">SearchResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.search(request, RequestOptions.DEFAULT);<br><br>    <span class="hljs-comment">//获取所有hits</span><br>    <span class="hljs-type">SearchHits</span> <span class="hljs-variable">hits</span> <span class="hljs-operator">=</span> response.getHits();<br><br>    System.out.println(hits.getTotalHits());<br>    System.out.println(response.getTook());<br><br>    <span class="hljs-comment">//遍历输出hits</span><br>    <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>        System.out.println(hit.getSourceAsString());<br>    &#125;<br>    <span class="hljs-comment">//关闭客户端连接</span><br>    client.close();<br>&#125;<br></code></pre></td></tr></table></figure>

<h6 id="3-分页查询"><a href="#3-分页查询" class="headerlink" title="3.分页查询"></a>3.分页查询</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 3.分页查询</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">queryByPage</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br>    <span class="hljs-comment">//创建ES客户端</span><br>    <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>            RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br>     <span class="hljs-comment">//3.分页查询</span><br>    <span class="hljs-type">SearchRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchRequest</span>();<br>    request.indices(<span class="hljs-string">&quot;user&quot;</span>);<br>    <span class="hljs-comment">//构建SearchSourceBuilder</span><br>    <span class="hljs-type">SearchSourceBuilder</span> <span class="hljs-variable">sourceBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchSourceBuilder</span>();<br>    <span class="hljs-comment">//查询所有数据</span><br>    sourceBuilder.query(QueryBuilders.matchAllQuery());<br><br>    <span class="hljs-comment">//分页查询，从第几页开始查</span><br>    sourceBuilder.from(<span class="hljs-number">2</span>);<br>    <span class="hljs-comment">//每页显示多少条</span><br>    sourceBuilder.size(<span class="hljs-number">2</span>);<br>    <span class="hljs-comment">//请求source</span><br>    request.source(sourceBuilder);<br>    <span class="hljs-type">SearchResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.search(request, RequestOptions.DEFAULT);<br><br>    <span class="hljs-comment">//获取所有hits</span><br>    <span class="hljs-type">SearchHits</span> <span class="hljs-variable">hits</span> <span class="hljs-operator">=</span> response.getHits();<br><br>    System.out.println(hits.getTotalHits());<br>    System.out.println(response.getTook());<br><br>    <span class="hljs-comment">//遍历输出hits</span><br>    <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>        System.out.println(hit.getSourceAsString());<br>    &#125;<br>    <span class="hljs-comment">//关闭客户端连接</span><br>    client.close();<br>&#125;<br></code></pre></td></tr></table></figure>

<h6 id="4-数据排序"><a href="#4-数据排序" class="headerlink" title="4.数据排序"></a>4.数据排序</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 4.排序</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">queryBySort</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br>    <span class="hljs-comment">//创建ES客户端</span><br>    <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>            RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br>    <span class="hljs-comment">//4.排序</span><br>    <span class="hljs-type">SearchRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchRequest</span>();<br>    request.indices(<span class="hljs-string">&quot;user&quot;</span>);<br>    <span class="hljs-comment">//构建SearchSourceBuilder</span><br>    <span class="hljs-type">SearchSourceBuilder</span> <span class="hljs-variable">sourceBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchSourceBuilder</span>();<br>    <span class="hljs-comment">//查询所有数据</span><br>    sourceBuilder.query(QueryBuilders.matchAllQuery());<br><br>    sourceBuilder.sort(<span class="hljs-string">&quot;age&quot;</span>, SortOrder.DESC);<br>    <span class="hljs-comment">//请求source</span><br>    request.source(sourceBuilder);<br>    <span class="hljs-type">SearchResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.search(request, RequestOptions.DEFAULT);<br><br>    <span class="hljs-comment">//获取所有hits</span><br>    <span class="hljs-type">SearchHits</span> <span class="hljs-variable">hits</span> <span class="hljs-operator">=</span> response.getHits();<br><br>    System.out.println(hits.getTotalHits());<br>    System.out.println(response.getTook());<br><br>    <span class="hljs-comment">//遍历输出hits</span><br>    <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>        System.out.println(hit.getSourceAsString());<br>    &#125;<br>    <span class="hljs-comment">//关闭客户端连接</span><br>    client.close();<br>&#125;<br></code></pre></td></tr></table></figure>

<h6 id="5-过滤字段"><a href="#5-过滤字段" class="headerlink" title="5.过滤字段"></a>5.过滤字段</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 5.过滤字段</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">queryByFilter</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br>    <span class="hljs-comment">//创建ES客户端</span><br>    <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>            RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>    <span class="hljs-comment">//5.过滤字段</span><br>    <span class="hljs-type">SearchRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchRequest</span>();<br>    request.indices(<span class="hljs-string">&quot;user&quot;</span>);<br>    <span class="hljs-comment">//构建SearchSourceBuilder</span><br>    <span class="hljs-type">SearchSourceBuilder</span> <span class="hljs-variable">sourceBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchSourceBuilder</span>();<br>    <span class="hljs-comment">//查询所有数据</span><br>    sourceBuilder.query(QueryBuilders.matchAllQuery());<br><br>    <span class="hljs-comment">//排除</span><br>    String[] excludes = &#123;<span class="hljs-string">&quot;age&quot;</span>&#125;;<br>    <span class="hljs-comment">//包括</span><br>    String[] includes = &#123;&#125;;<br><br>    sourceBuilder.fetchSource(includes, excludes);<br><br>    <span class="hljs-comment">//请求source</span><br>    request.source(sourceBuilder);<br>    <span class="hljs-type">SearchResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.search(request, RequestOptions.DEFAULT);<br><br>    <span class="hljs-comment">//获取所有hits</span><br>    <span class="hljs-type">SearchHits</span> <span class="hljs-variable">hits</span> <span class="hljs-operator">=</span> response.getHits();<br><br>    System.out.println(hits.getTotalHits());<br>    System.out.println(response.getTook());<br><br>    <span class="hljs-comment">//遍历输出hits</span><br>    <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>        System.out.println(hit.getSourceAsString());<br>    &#125;<br>    <span class="hljs-comment">//关闭客户端连接</span><br>    client.close();<br>&#125;<br></code></pre></td></tr></table></figure>

<h6 id="6-Bool-查询"><a href="#6-Bool-查询" class="headerlink" title="6.Bool 查询"></a>6.Bool 查询</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 6.组合查询</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">queryByConditionGroup</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br>    <span class="hljs-comment">//创建ES客户端</span><br>    <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>            RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>     <span class="hljs-comment">//6.组合查询</span><br>    <span class="hljs-type">SearchRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchRequest</span>();<br>    request.indices(<span class="hljs-string">&quot;user&quot;</span>);<br>    <span class="hljs-comment">//构建SearchSourceBuilder</span><br>    <span class="hljs-type">SearchSourceBuilder</span> <span class="hljs-variable">sourceBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchSourceBuilder</span>();<br>    <span class="hljs-comment">//bool查询构建</span><br>    <span class="hljs-type">BoolQueryBuilder</span> <span class="hljs-variable">boolQueryBuilder</span> <span class="hljs-operator">=</span> QueryBuilders.boolQuery();<br>    <span class="hljs-comment">//必须包含</span><br>    boolQueryBuilder.must(QueryBuilders.matchQuery(<span class="hljs-string">&quot;age&quot;</span>,<span class="hljs-string">&quot;30&quot;</span>));<br>    <span class="hljs-comment">//一定不含</span><br>    boolQueryBuilder.mustNot(QueryBuilders.matchQuery(<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;zhangsan&quot;</span>));<br>    <span class="hljs-comment">//可能包含</span><br>    boolQueryBuilder.should(QueryBuilders.matchQuery(<span class="hljs-string">&quot;sex&quot;</span>, <span class="hljs-string">&quot;男&quot;</span>));<br>    sourceBuilder.query(boolQueryBuilder);<br><br>    <span class="hljs-comment">//请求source</span><br>    request.source(sourceBuilder);<br><br>    <span class="hljs-type">SearchResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.search(request, RequestOptions.DEFAULT);<br><br>    <span class="hljs-comment">//获取所有hits</span><br>    <span class="hljs-type">SearchHits</span> <span class="hljs-variable">hits</span> <span class="hljs-operator">=</span> response.getHits();<br><br>    System.out.println(hits.getTotalHits());<br>    System.out.println(response.getTook());<br><br>    <span class="hljs-comment">//遍历输出hits</span><br>    <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>        System.out.println(hit.getSourceAsString());<br>    &#125;<br>    <span class="hljs-comment">//关闭客户端连接</span><br>    client.close();<br>&#125;<br></code></pre></td></tr></table></figure>

<h6 id="7-范围查询"><a href="#7-范围查询" class="headerlink" title="7.范围查询"></a>7.范围查询</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 7.范围查询</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">queryByRange</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br>    <span class="hljs-comment">//创建ES客户端</span><br>    <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>            RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>    <span class="hljs-comment">//7.f范围查询</span><br>    <span class="hljs-type">SearchRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchRequest</span>();<br>    request.indices(<span class="hljs-string">&quot;user&quot;</span>);<br>    <span class="hljs-comment">//构建SearchSourceBuilder</span><br>    <span class="hljs-type">SearchSourceBuilder</span> <span class="hljs-variable">sourceBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchSourceBuilder</span>();<br>    <span class="hljs-comment">//范围查询构建</span><br>    <span class="hljs-type">RangeQueryBuilder</span> <span class="hljs-variable">rangeQuery</span> <span class="hljs-operator">=</span> QueryBuilders.rangeQuery(<span class="hljs-string">&quot;age&quot;</span>);<br>    <span class="hljs-comment">//大于等于</span><br>    rangeQuery.gte(<span class="hljs-number">30</span>);<br>    <span class="hljs-comment">//小于等于</span><br>    <span class="hljs-comment">//rangeQuery.lte(40);</span><br>    <span class="hljs-comment">//小于不等于</span><br>    rangeQuery.lt(<span class="hljs-number">40</span>);<br><br>    sourceBuilder.query(rangeQuery);<br><br>    <span class="hljs-comment">//请求source</span><br>    request.source(sourceBuilder);<br><br>    <span class="hljs-type">SearchResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.search(request, RequestOptions.DEFAULT);<br><br>    <span class="hljs-comment">//获取所有hits</span><br>    <span class="hljs-type">SearchHits</span> <span class="hljs-variable">hits</span> <span class="hljs-operator">=</span> response.getHits();<br><br>    System.out.println(hits.getTotalHits());<br>    System.out.println(response.getTook());<br><br>    <span class="hljs-comment">//遍历输出hits</span><br>    <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>        System.out.println(hit.getSourceAsString());<br>    &#125;<br>    <span class="hljs-comment">//关闭客户端连接</span><br>    client.close();<br>&#125;<br></code></pre></td></tr></table></figure>

<h6 id="8-模糊查询"><a href="#8-模糊查询" class="headerlink" title="8.模糊查询"></a>8.模糊查询</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 8.模糊查询</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">queryByLike</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br>    <span class="hljs-comment">//创建ES客户端</span><br>    <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>            RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>    <span class="hljs-comment">//8.模糊查询</span><br>    <span class="hljs-type">SearchRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchRequest</span>();<br>    request.indices(<span class="hljs-string">&quot;user&quot;</span>);<br>    <span class="hljs-comment">//构建SearchSourceBuilder</span><br>    <span class="hljs-type">SearchSourceBuilder</span> <span class="hljs-variable">sourceBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchSourceBuilder</span>();<br><br>    <span class="hljs-comment">//模糊查询 fuzzyQuery, Fuzziness.ONE 模糊字符控制在1个以内</span><br>    <span class="hljs-type">FuzzyQueryBuilder</span> <span class="hljs-variable">fuzzyQueryBuilder</span> <span class="hljs-operator">=</span> QueryBuilders.fuzzyQuery(<span class="hljs-string">&quot;name&quot;</span>, <span class="hljs-string">&quot;wangw&quot;</span>).fuzziness(Fuzziness.TWO);<br><br>    sourceBuilder.query(fuzzyQueryBuilder);<br><br>    <span class="hljs-comment">//请求source</span><br>    request.source(sourceBuilder);<br><br>    <span class="hljs-type">SearchResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.search(request, RequestOptions.DEFAULT);<br><br>    <span class="hljs-comment">//获取所有hits</span><br>    <span class="hljs-type">SearchHits</span> <span class="hljs-variable">hits</span> <span class="hljs-operator">=</span> response.getHits();<br><br>    System.out.println(hits.getTotalHits());<br>    System.out.println(response.getTook());<br><br>    <span class="hljs-comment">//遍历输出hits</span><br>    <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>        System.out.println(hit.getSourceAsString());<br>    &#125;<br><br>    <span class="hljs-comment">//关闭客户端连接</span><br>    client.close();<br>&#125;<br></code></pre></td></tr></table></figure>

<p>9.高亮查询</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 9.高亮查询</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">queryByHighlight</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br>    <span class="hljs-comment">//创建ES客户端</span><br>    <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>            RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br>    <span class="hljs-comment">//9.高亮查询</span><br>    <span class="hljs-type">SearchRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchRequest</span>();<br>    request.indices(<span class="hljs-string">&quot;user&quot;</span>);<br>    <span class="hljs-comment">//构建SearchSourceBuilder</span><br>    <span class="hljs-type">SearchSourceBuilder</span> <span class="hljs-variable">sourceBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchSourceBuilder</span>();<br><br>    <span class="hljs-comment">//构建查询</span><br>    <span class="hljs-type">TermQueryBuilder</span> <span class="hljs-variable">termQueryBuilder</span> <span class="hljs-operator">=</span> QueryBuilders.termQuery(<span class="hljs-string">&quot;name&quot;</span>, <span class="hljs-string">&quot;zhangsan&quot;</span>);<br><br>    <span class="hljs-comment">//构建高亮字段</span><br>    <span class="hljs-type">HighlightBuilder</span> <span class="hljs-variable">highlightBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">HighlightBuilder</span>();<br>    <span class="hljs-comment">//前缀标签</span><br>    highlightBuilder.preTags(<span class="hljs-string">&quot;&lt;font color = red&gt;&quot;</span>);<br>    <span class="hljs-comment">//后缀标签</span><br>    highlightBuilder.postTags(<span class="hljs-string">&quot;&lt;/font&gt;&quot;</span>);<br>    <span class="hljs-comment">//高亮字段</span><br>    highlightBuilder.field(<span class="hljs-string">&quot;name&quot;</span>);<br>    <span class="hljs-comment">//设置高亮对象</span><br>    sourceBuilder.highlighter(highlightBuilder);<br><br>    <span class="hljs-comment">//设置查询</span><br>    sourceBuilder.query(termQueryBuilder);<br><br>    <span class="hljs-comment">//请求source</span><br>    request.source(sourceBuilder);<br><br>    <span class="hljs-type">SearchResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.search(request, RequestOptions.DEFAULT);<br><br>    <span class="hljs-comment">//获取所有hits</span><br>    <span class="hljs-type">SearchHits</span> <span class="hljs-variable">hits</span> <span class="hljs-operator">=</span> response.getHits();<br><br>    System.out.println(response);<br>    System.out.println(hits.getTotalHits());<br>    System.out.println(response.getTook());<br><br>    <span class="hljs-comment">//遍历输出hits</span><br>    <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>        System.out.println(hit.getSourceAsString());<br>    &#125;<br><br>    <span class="hljs-comment">//关闭客户端连接</span><br>    client.close();<br>&#125;<br></code></pre></td></tr></table></figure>

<p>10.聚合查询</p>
<ul>
<li>最大年龄</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 10.聚合查询  最大年龄查询</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">queryByGroup</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br>    <span class="hljs-comment">//创建ES客户端</span><br>    <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>            RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>    <span class="hljs-comment">//10.聚合查询  最大年龄查询</span><br>    <span class="hljs-type">SearchRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchRequest</span>();<br>    request.indices(<span class="hljs-string">&quot;user&quot;</span>);<br>    <span class="hljs-comment">//构建SearchSourceBuilder</span><br>    <span class="hljs-type">SearchSourceBuilder</span> <span class="hljs-variable">sourceBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchSourceBuilder</span>();<br><br>    <span class="hljs-comment">//聚合builder AggregationBuilders</span><br>    <span class="hljs-type">MaxAggregationBuilder</span> <span class="hljs-variable">aggregationBuilder</span> <span class="hljs-operator">=</span> AggregationBuilders.max(<span class="hljs-string">&quot;maxAge&quot;</span>).field(<span class="hljs-string">&quot;age&quot;</span>);<br>    sourceBuilder.aggregation(aggregationBuilder);<br><br>    <span class="hljs-comment">//请求source</span><br>    request.source(sourceBuilder);<br><br>    <span class="hljs-type">SearchResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.search(request, RequestOptions.DEFAULT);<br><br>    <span class="hljs-comment">//获取所有hits</span><br>    <span class="hljs-type">SearchHits</span> <span class="hljs-variable">hits</span> <span class="hljs-operator">=</span> response.getHits();<br><br>    System.out.println(response);<br>    System.out.println(hits.getTotalHits());<br>    System.out.println(response.getTook());<br><br>    <span class="hljs-comment">//遍历输出hits</span><br>    <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>        System.out.println(hit.getSourceAsString());<br>    &#125;<br><br>    <span class="hljs-comment">//关闭客户端连接</span><br>    client.close();<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li>分组查询</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 11.分组查询  年龄分组</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">queryByGroupBy</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br>    <span class="hljs-comment">//创建ES客户端</span><br>    <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RestHighLevelClient</span>(<br>            RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(<span class="hljs-string">&quot;localhost&quot;</span>,<span class="hljs-number">9200</span>)));<br><br>    <span class="hljs-comment">//11.分组查询  年龄分组</span><br>    <span class="hljs-type">SearchRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchRequest</span>();<br>    request.indices(<span class="hljs-string">&quot;user&quot;</span>);<br>    <span class="hljs-comment">//构建SearchSourceBuilder</span><br>    <span class="hljs-type">SearchSourceBuilder</span> <span class="hljs-variable">sourceBuilder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SearchSourceBuilder</span>();<br><br>    <span class="hljs-comment">//分组builder AggregationBuilders 分组terms</span><br>    <span class="hljs-type">TermsAggregationBuilder</span> <span class="hljs-variable">aggregationBuilder</span> <span class="hljs-operator">=</span> AggregationBuilders.terms(<span class="hljs-string">&quot;ageGroup&quot;</span>).field(<span class="hljs-string">&quot;age&quot;</span>);<br>    sourceBuilder.aggregation(aggregationBuilder);<br><br>    <span class="hljs-comment">//请求source</span><br>    request.source(sourceBuilder);<br><br>    <span class="hljs-type">SearchResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> client.search(request, RequestOptions.DEFAULT);<br><br>    <span class="hljs-comment">//获取所有hits</span><br>    <span class="hljs-type">SearchHits</span> <span class="hljs-variable">hits</span> <span class="hljs-operator">=</span> response.getHits();<br><br>    System.out.println(response);<br>    System.out.println(hits.getTotalHits());<br>    System.out.println(response.getTook());<br><br>    <span class="hljs-comment">//遍历输出hits</span><br>    <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>        System.out.println(hit.getSourceAsString());<br>    &#125;<br><br>    <span class="hljs-comment">//关闭客户端连接</span><br>    client.close();<br>&#125;<br></code></pre></td></tr></table></figure>



<h2 id="第3章-Elasticsearch-环境"><a href="#第3章-Elasticsearch-环境" class="headerlink" title="第3章 Elasticsearch 环境"></a>第3章 Elasticsearch 环境</h2><h3 id="3-1-相关概念"><a href="#3-1-相关概念" class="headerlink" title="3.1 相关概念"></a>3.1 相关概念</h3><h4 id="3-1-1-单机-amp-集群"><a href="#3-1-1-单机-amp-集群" class="headerlink" title="3.1.1 单机 &amp; 集群"></a>3.1.1 单机 &amp; 集群</h4><p>​		单台 Elasticsearch 服务器提供服务，往往都有最大的负载能力，超过这个阈值，服务器性能就会大大降低甚至不可用，所以生产环境中，一般都是运行在指定服务器集群中。 </p>
<p>​		除了负载能力，单点服务器也存在其他问题：</p>
<ul>
<li>单台机器存储容量有限</li>
<li>单台服务器容易出现单点故障，无法实现高可用</li>
<li>但服务的并发处理能力有限</li>
</ul>
<p>配置服务器集群时，集群中节点数量没有限制，大于等于 2 个节点就可以看做是集群了。一 般出于高性能及高可用方面来考虑集群中节点数量都是 3 个以上。</p>
<h4 id="3-1-2-集群-Cluster"><a href="#3-1-2-集群-Cluster" class="headerlink" title="3.1.2 集群 Cluster"></a>3.1.2 集群 Cluster</h4><p>​		一个集群就是由一个或多个服务器节点组织在一起，共同持有整个的数据，并一起提供索引和搜索功能。一个 Elasticsearch 集群有一个唯一的名字标识，这个名字默认就 是”elasticsearch”。这个名字是重要的，因为一个节点只能通过指定某个集群的名字，来加入这个集群。</p>
<h4 id="3-1-3-节点-Node"><a href="#3-1-3-节点-Node" class="headerlink" title="3.1.3 节点 Node"></a>3.1.3 节点 Node</h4><p>​		集群中包含很多服务器，一个节点就是其中的一个服务器。作为集群的一部分，它存储数据，参与集群的索引和搜索功能。 </p>
<p>​		一个节点也是由一个名字来标识的，默认情况下，这个名字是一个随机的漫威漫画角色的名字，这个名字会在启动的时候赋予节点。这个名字对于管理工作来说挺重要的，因为在 这个管理过程中，你会去确定网络中的哪些服务器对应于 Elasticsearch 集群中的哪些节点。 </p>
<p>​		一个节点可以通过配置集群名称的方式来加入一个指定的集群。默认情况下，每个节点都会被安排加入到一个叫做“elasticsearch”的集群中，这意味着，如果你在你的网络中启动了 若干个节点，并假定它们能够相互发现彼此，它们将会自动地形成并加入到一个叫做 “elasticsearch”的集群中。</p>
<p>​		在一个集群里，只要你想，可以拥有任意多个节点。而且，如果当前你的网络中没有运行任何 Elasticsearch 节点，这时启动一个节点，会默认创建并加入一个叫做“elasticsearch”的 集群。</p>
<h2 id="第4章-Elasticsearch-进阶"><a href="#第4章-Elasticsearch-进阶" class="headerlink" title="第4章 Elasticsearch 进阶"></a>第4章 Elasticsearch 进阶</h2><h3 id="4-1-核心概念"><a href="#4-1-核心概念" class="headerlink" title="4.1 核心概念"></a>4.1 核心概念</h3><h4 id="4-1-1-索引（Index）"><a href="#4-1-1-索引（Index）" class="headerlink" title="4.1.1 索引（Index）"></a>4.1.1 索引（Index）</h4><p>​		一个索引就是一个拥有几分相似特征的文档的集合。比如说，你可以有一个客户数据的索引，另一个产品目录的索引，还有一个订单数据的索引。一个索引由一个名字来标识（必须全部是小写字母），并且当我们要对这个索引中的文档进行索引、搜索、更新和删除的时候，都要使用到这个名字。在一个集群中，可以定义任意多的索引。</p>
<p>​		 能搜索的数据必须索引，这样的好处是可以提高查询速度，比如：新华字典前面的目录 就是索引的意思，目录可以提高查询速度。</p>
<p>​		$\textcolor{blue}{Elasticsearch 索引的精髓：一切设计都是为了提高搜索的性能。}$</p>
<h4 id="4-1-2-类型（Type）"><a href="#4-1-2-类型（Type）" class="headerlink" title="4.1.2 类型（Type）"></a>4.1.2 类型（Type）</h4><p>​		在一个索引中，你可以定义一种或多种类型。 </p>
<p>​		一个类型是你的索引的一个逻辑上的分类&#x2F;分区，其语义完全由你来定。通常，会为具有一组共同字段的文档定义一个类型。不同的版本，类型发生了不同的变化</p>
<p><img src="/blog/ElasticSearch.assets/image-20220808165946817.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808165946817"></p>
<h4 id="4-1-3-文档（Document）"><a href="#4-1-3-文档（Document）" class="headerlink" title="4.1.3 文档（Document）"></a>4.1.3 文档（Document）</h4><p>​		一个文档是一个可被索引的基础信息单元，也就是一条数据</p>
<p>​		比如：你可以拥有某一个客户的文档，某一个产品的一个文档，当然，也可以拥有某个订单的一个文档。文档以 JSON（Javascript Object Notation）格式来表示，而 JSON 是一个 到处存在的互联网数据交互格式。 </p>
<p>​		在一个 index&#x2F;type 里面，你可以存储任意多的文档。</p>
<h4 id="4-1-3-字段（Field）"><a href="#4-1-3-字段（Field）" class="headerlink" title="4.1.3 字段（Field）"></a>4.1.3 字段（Field）</h4><p>​		相当于是数据表的字段，对文档数据根据不同属性进行的分类标识</p>
<h4 id="4-1-5-映射（Mapping）"><a href="#4-1-5-映射（Mapping）" class="headerlink" title="4.1.5 映射（Mapping）"></a>4.1.5 映射（Mapping）</h4><p>​		mapping 是处理数据的方式和规则方面做一些限制，如：某个字段的数据类型、默认值、 分析器、是否被索引等等。这些都是映射里面可以设置的，其它就是处理 ES 里面数据的一 些使用规则设置也叫做映射，按着最优规则处理数据对性能提高很大，因此才需要建立映射， 并且需要思考如何建立映射才能对性能更好。</p>
<h4 id="4-1-6-分片（Shards）"><a href="#4-1-6-分片（Shards）" class="headerlink" title="4.1.6 分片（Shards）"></a>4.1.6 分片（Shards）</h4><p>​		一个索引可以存储超出单个节点硬件限制的大量数据。比如，一个具有 10 亿文档数据 的索引占据 1TB 的磁盘空间，而任一节点都可能没有这样大的磁盘空间。或者单个节点处 理搜索请求，响应太慢。为了解决这个问题，Elasticsearch 提供了将索引划分成多份的能力， 每一份就称之为分片。当你创建一个索引的时候，你可以指定你想要的分片的数量。每个分 片本身也是一个功能完善并且独立的“索引”，这个“索引”可以被放置到集群中的任何节点 上。 </p>
<p>​		分片很重要，主要有两方面的原因：</p>
<ul>
<li>允许你水平分割&#x2F;扩展你的内容容量</li>
<li>允许你在分片上进行分布式、并行的操作，进而提高性能&#x2F;吞吐量。</li>
</ul>
<p>​		至于一个分片怎样分布，它的文档怎样聚合和搜索请求，是完全由 Elasticsearch 管理的， 对于作为用户的你来说，这些都是透明的，无需过分关心。</p>
<p>​		被混淆的概念是，一个 Lucene 索引 我们在 Elasticsearch 称作 分片 。 一个 Elasticsearch 索引 是分片的集合。 当 Elasticsearch 在索引中搜索的时候， 他发送查询 到每一个属于索引的分片(Lucene 索引)，然后合并每个分片的结果到一个全局的结果集。</p>
<h4 id="4-1-7-副本（Replicas）"><a href="#4-1-7-副本（Replicas）" class="headerlink" title="4.1.7 副本（Replicas）"></a>4.1.7 副本（Replicas）</h4><p>​		在一个网络 &#x2F; 云的环境里，失败随时都可能发生，在某个分片&#x2F;节点不知怎么的就处于 离线状态，或者由于任何原因消失了，这种情况下，有一个故障转移机制是非常有用并且是 强烈推荐的。为此目的，Elasticsearch 允许你创建分片的一份或多份拷贝，这些拷贝叫做复 制分片(副本)。</p>
<p>​		复制分片之所以重要，有两个主要原因：</p>
<ul>
<li>在分片&#x2F;节点失败的情况下，提供了高可用性。因为这个原因，注意到复制分片从不与 原&#x2F;主要（original&#x2F;primary）分片置于同一节点上是非常重要的。 </li>
<li>扩展你的搜索量&#x2F;吞吐量，因为搜索可以在所有的副本上并行运行。</li>
</ul>
<p>​		总之，每个索引可以被分成多个分片。一个索引也可以被复制 0 次（意思是没有复制） 或多次。一旦复制了，每个索引就有了主分片（作为复制源的原来的分片）和复制分片（主 分片的拷贝）之别。分片和复制的数量可以在索引创建的时候指定。在索引创建之后，你可 以在任何时候动态地改变复制的数量，但是你事后不能改变分片的数量。默认情况下， Elasticsearch 中的每个索引被分片 1 个主分片和 1 个复制，这意味着，如果你的集群中至少 有两个节点，你的索引将会有 1 个主分片和另外 1 个复制分片（1 个完全拷贝），这样的话 每个索引总共就有 2 个分片，我们需要根据索引需要确定分片个数。</p>
<h4 id="4-1-8-分配（Allocation）"><a href="#4-1-8-分配（Allocation）" class="headerlink" title="4.1.8 分配（Allocation）"></a>4.1.8 分配（Allocation）</h4><p>​		将分片分配给某个节点的过程，包括分配主分片或者副本。如果是副本，还包含从主分 片复制数据的过程。这个过程是由 master 节点完成的。</p>
<h3 id="4-2-系统架构"><a href="#4-2-系统架构" class="headerlink" title="4.2 系统架构"></a>4.2 系统架构</h3><p><img src="/blog/ElasticSearch.assets/image-20220808171108140.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220808171108140"></p>
<p>​		一个运行中的 Elasticsearch 实例称为一个节点，而集群是由一个或者多个拥有相同 cluster.name 配置的节点组成， 它们共同承担数据和负载的压力。当有节点加入集群中或者 从集群中移除节点时，集群将会重新平均分布所有的数据。 		<strong>当一个节点被选举成为主节点时， 它将负责管理集群范围内的所有变更</strong>，例如增加、 删除索引，或者增加、删除节点等。 而主节点并不需要涉及到文档级别的变更和搜索等操 作，所以当集群只拥有一个主节点的情况下，即使流量的增加它也不会成为瓶颈。 任何节点都可以成为主节点。</p>
<p>​		 作为用户，我们可以将请求发送到集群中的任何节点 ，包括主节点。 每个节点都知道任意文档所处的位置，并且能够将我们的请求直接转发到存储我们所需文档的节点。 无论我们将请求发送到哪个节点，它都能负责从各个包含我们所需文档的节点收集回数据，并将最终结果返回給客户端。 Elasticsearch 对这一切的管理都是透明的。</p>
<h3 id="4-3-分布式集群"><a href="#4-3-分布式集群" class="headerlink" title="4.3 分布式集群"></a>4.3 分布式集群</h3><h4 id="4-3-1-单节点集群"><a href="#4-3-1-单节点集群" class="headerlink" title="4.3.1 单节点集群"></a>4.3.1 单节点集群</h4><p>​		在包含一个空节点的集群内创建名为 users 的索引，为了演示目的，我们将分配 3 个主分片和一份副本（每个主分片拥有一个副本分片）</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;settings&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;number_of_shards&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-attr">&quot;number_of_replicas&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p><img src="/blog/ElasticSearch.assets/image-20220809092004300.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809092004300"></p>
<p>集群现在是拥有一个索引的单节点集群。所有 3 个主分片都被分配在 node-1 。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809092056886.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809092056886"></p>
<p>通过 elasticsearch-head 插件查看集群情况</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809092858502.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809092858502"></p>
<p>$\textcolor{GreenYellow}{集群健康值:yellow( 3 of 6 ) }$: 表示当前集群的全部主分片都正常运行，但是副本分片没有全部处在正常状 态</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809092652963.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809092652963">:3个主分片正常</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809092715193.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809092715193">：: 3 个副本分片都是 Unassigned —— 它们都没有被分配到任何节点。 在同 一个节点上既保存原始数据又保存副本是没有意义的，因为一旦失去了那个节点，我们也将丢失该节点 上的所有副本数据。</p>
<p>当前集群是正常运行的，但是在硬件故障时有丢失数据的风险。</p>
<h4 id="4-3-2-故障转移"><a href="#4-3-2-故障转移" class="headerlink" title="4.3.2 故障转移"></a>4.3.2 故障转移</h4><p>​		当集群中只有一个节点在运行时，意味着会有一个单点故障问题——没有冗余。 幸运的是，我们只需再启动一个节点即可防止数据丢失。当你在同一台机器上启动了第二个节点 时，只要它和第一个节点有同样的 cluster.name 配置，它就会自动发现集群并加入到其中。 但是在不同机器上启动节点的时候，为了加入到同一集群，你需要配置一个可连接到的单播主机列表。之所以配置为使用单播发现，以防止节点无意中加入集群。只有在同一台机器上运行的节点才会自动组成集群。</p>
<p>​		 如果启动了第二个节点，我们的集群将会拥有两个节点的集群 : 所有主分片和副本分片都已被分配</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809092835439.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809092835439"></p>
<p>通过 elasticsearch-head 插件查看集群情况</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809093017069.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809093017069"></p>
<p>$\textcolor{green}{集群健康值:green( 6 of 6 )}$ : 表示所有 6 个分片（包括 3 个主分片和 3 个副本分片）都在正常运行。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809093253929.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809093253929">:3 个主分片正常</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809093308298.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809093308298">:当第二个节点加入到集群后，3 个副本分片将会分配到这个节点上——每 个主分片对应一个副本分片。这意味着当集群内任何一个节点出现问题时，我们的数据都完好无损。所有新近被索引的文档都将会保存在主分片上，然后被并行的复制到对应的副本分片上。这就保证了我们既可以从主分片又可以从副本分片上获得文档。</p>
<h4 id="4-3-3-水平扩容"><a href="#4-3-3-水平扩容" class="headerlink" title="4.3.3 水平扩容"></a>4.3.3 水平扩容</h4><p>怎样为正在增长中的应用程序按需扩容呢？当启动了第三个节点，我们的集群将 会拥有三个节点的集群 : 为了分散负载而对分片进行重新分配</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809093421363.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809093421363"></p>
<p>通过 elasticsearch-head 插件查看集群情况</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809093555823.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809093555823"></p>
<p>$\textcolor{green}{集群健康值:green( 6 of 6 )}$ :表示所有 6 个分片（包括 3 个主分片和 3 个副本分片）都在正常运行。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809093653734.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809093653734"></p>
<p>​		Node 1 和 Node 2 上各有一个分片被迁移到了新的 Node 3 节点，现在每个节点上都拥有 2 个分片， 而不是之前的 3 个。 这表示每个节点的硬件资源（CPU, RAM, I&#x2F;O）将被更少的分片所共享，每个分片的性能将会得到提升。 </p>
<p>​		<strong>分片是一个功能完整的搜索引擎</strong>，它拥有使用一个节点上的所有资源的能力。 我们这个拥有 6 个分 片（3 个主分片和 3 个副本分片）的索引可以最大扩容到 6 个节点，每个节点上存在一个分片，并且每个分片拥有所在节点的全部资源。</p>
<blockquote>
<p>但是如果我们想要扩容超过 6 个节点怎么办呢？</p>
</blockquote>
<p>​		主分片的数目在索引创建时就已经确定了下来。实际上，这个数目定义了这个索引能够存储的最大数据量。（实际大小取决于你的数据、硬件和使用场景。） 但是，读操作—— 搜索和返回数据——可以同时被主分片 或 副本分片所处理，所以当你拥有越多的副本分片时，也将拥有越高的吞吐量。 在运行中的集群上是可以动态调整副本分片数目的，我们可以按需伸缩集群。让我们把副本数从默认的 1 增加到2</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br> 	<span class="hljs-attr">&quot;number_of_replicas&quot;</span> <span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p><img src="/blog/ElasticSearch.assets/image-20220809094306788.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809094306788"></p>
<p>​		users 索引现在拥有 9 个分片：3 个主分片和 6 个副本分片。 这意味着我们可以将集群 扩容到 9 个节点，每个节点上一个分片。相比原来 3 个节点时，集群搜索性能可以提升 3 倍。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809094556062.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809094556062"></p>
<p>通过 elasticsearch-head 插件查看集群情况</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809094618038.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809094618038"></p>
<p>​		当然，如果只是在相同节点数目的集群上增加更多的副本分片并不能提高性能，因为每个分片从节点上获得的资源会变少。 你需要增加更多的硬件资源来提升吞吐量。 但是更多的副本分片数提高了数据冗余量：按照上面的节点配置，我们可以在失去 2 个节点 的情况下不丢失任何数据。</p>
<h4 id="4-3-4-应对故障"><a href="#4-3-4-应对故障" class="headerlink" title="4.3.4 应对故障"></a>4.3.4 应对故障</h4><p>​		关闭第一个节点，这时集群的状态为:关闭了一个节点后的集群。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809094735565.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809094735565"></p>
<p>​		关闭的节点是一个主节点。而集群必须拥有一个主节点来保证正常工作，所以发生的第一件事情就是选举一个新的主节点： Node 2 。在我们关闭 Node 1 的同时也失去了主分片 1 和 2 ，并且在缺失主分片的时候索引也不能正常工作。 如果此时来检查集群的状况，我们看到的状态将会为 red ：不是所有主分片都在正常工作。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809095028661.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809095028661"></p>
<p>​		幸运的是，在其它节点上存在着这两个主分片的完整副本， 所以新的主节点立即将这些分片在 Node 2 和 Node 3 上对应的副本分片提升为主分片， 此时集群的状态将会为 yellow。这个提升主分片的过程是瞬间发生的，如同按下一个开关一般。</p>
<blockquote>
<p>为什么集群状态是 yellow 而不是 green 呢？</p>
</blockquote>
<p>​		虽然拥有所有的三个主分片，但是同时设置了每个主分片需要对应 2 份副本分片，而此时只存在一份副本分片。 所以集群不能为 green 的状态，不过我们不必过于担心：如果我 同样关闭了 Node 2 ，我们的程序依然可以保持在不丢任何数据的情况下运行，因为 Node 3 为每一个分片都保留着一份副本</p>
<p>​		如果重新启动 Node 1 ，集群可以将缺失的副本分片再次进行分配，那么集群的状态也将恢复成之前的状态。 如果 Node 1 依然拥有着之前的分片，它将尝试去重用它们， 同时仅从主分片复制发生了修改的数据文件。和之前的集群相比，只是 Master 节点切换了。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809095750907.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809095750907"></p>
<p>可以发送请求到集群中的任一节点。 每个节点都有能力处理任意请求。 每个节点都知道集群中任一文档位置，所以可以直接将请求转发到需要的节点上。 在下面的例子中，将所有的请求发送到 Node 1，我们将其称为 <strong>协调节点(coordinating node)</strong> 。</p>
<blockquote>
<p>当发送请求的时候， 为了扩展负载，更好的做法是轮询集群中所有的节点。</p>
</blockquote>
<h4 id="4-5-1-写流程"><a href="#4-5-1-写流程" class="headerlink" title="4.5.1 写流程"></a>4.5.1 写流程</h4><p>​		新建、索引和删除 请求都是 <strong>写</strong> 操作， 必须在主分片上面完成之后才能被复制到相关的副本分片</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809100040461.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809100040461"></p>
<p><strong>新建，索引和删除文档所需要的步骤顺序：</strong></p>
<ol>
<li>客户端向 Node 1 发送新建、索引或者删除请求。</li>
<li>节点使用文档的 _id 确定文档属于分片 0 。请求会被转发到 Node 3，因为分片 0 的 主分片目前被分配在 Node 3 上。 </li>
<li>Node 3 在主分片上面执行请求。如果成功了，它将请求并行转发到 Node 1 和 Node 2  的副本分片上。一旦所有的副本分片都报告成功, Node 3 将向协调节点报告成功，协调节点向客户端报告成功</li>
</ol>
<p>​		在客户端收到成功响应时，文档变更已经在主分片和所有副本分片执行完成，变更是安全的。 有一些可选的请求参数允许您影响这个过程，可能以数据安全为代价提升性能。这些选项很少使用，因为 Elasticsearch 已经很快，但是为了完整起见，请参考下面表格：</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>consistency</td>
<td>consistency，即一致性。在默认设置下，即使仅仅是在试图执行一个_写_操作之 前，主分片都会要求 必须要有 规定数量(quorum)（或者换种说法，也即必须要 有大多数）的分片副本处于活跃可用状态，才会去执行_写_操作(其中分片副本 可以是主分片或者副本分片)。这是为了避免在发生网络分区故障（network  partition）的时候进行_写_操作，进而导致数据不一致。<em>规定数量_即：<br> <strong>int( (primary + number_of_replicas) &#x2F; 2 ) + 1</strong> <br><br>consistency 参数的值可以设为 one （只要主分片状态 ok 就允许执行_写_操 作）,all（必须要主分片和所有副本分片的状态没问题才允许执行_写_操作）, 或 quorum 。默认值为 quorum , **即大多数的分片副本状态没问题就允许执行_写</em> 操作。** <br><br>注意，规定数量 的计算公式中 number_of_replicas 指的是在索引设置中的设定 副本分片数，而不是指当前处理活动状态的副本分片数。如果你的索引设置中指定了当前索引拥有三个副本分片，那规定数量的计算结果即： <br><strong>int( (primary + 3 replicas) &#x2F; 2 ) + 1 &#x3D; 3</strong> <br>如果此时你只启动两个节点，那么处于活跃状态的分片副本数量就达不到规定数 量，也因此您将无法索引和删除任何文档。</td>
</tr>
<tr>
<td>timeout</td>
<td>如果没有足够的副本分片会发生什么？ Elasticsearch 会等待，希望更多的分片出 现。默认情况下，它最多等待 1 分钟。 如果你需要，你可以使用 timeout 参数 使它更早终止： 100 100 毫秒，30s 是 30 秒。</td>
</tr>
</tbody></table>
<blockquote>
<p><strong>note：</strong>新索引默认有 1 个副本分片，这意味着为满足规定数量应该需要两个活动的分片副本。 但是，这些 默认的设置会阻止我们在单一节点上做任何事情。为了避免这个问题，要求只有当 number_of_replicas 大 于 1 的时候，规定数量才会执行。</p>
</blockquote>
<h4 id="4-5-2-读流程"><a href="#4-5-2-读流程" class="headerlink" title="4.5.2 读流程"></a>4.5.2 读流程</h4><p>​		我们可以从主分片或者从其它任意副本分片检索文档</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809101154287.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809101154287"></p>
<p><strong>从主分片或者副本分片检索文档的步骤顺序：</strong></p>
<ol>
<li>客户端向 Node 1 发送获取请求。 </li>
<li>节点使用文档的 _id 来确定文档属于分片 0 。分片 0 的副本分片存在于所有的三个节点上。 在这种情况下，它将请求转发到 Node 2 。</li>
<li>Node 2 将文档返回给 Node 1 ，然后将文档返回给客户端。</li>
</ol>
<p>​		在处理读取请求时，协调结点在每次请求的时候都会通过轮询所有的副本分片来达到负载均衡。在文档被检索时，已经被索引的文档可能已经存在于主分片上但是还没有复制到副本分 片。 在这种情况下，副本分片可能会报告文档不存在，但是主分片可能成功返回文档。 一 旦索引请求成功返回给用户，文档在主分片和副本分片都是可用的。</p>
<h4 id="4-5-3-更新流程"><a href="#4-5-3-更新流程" class="headerlink" title="4.5.3 更新流程"></a>4.5.3 更新流程</h4><p>​		部分更新一个文档结合了先前说明的读取和写入流程：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809101406451.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809101406451"></p>
<p><strong>部分更新一个文档的步骤如下：</strong></p>
<ol>
<li>客户端向 Node 1 发送更新请求。 </li>
<li>它将请求转发到主分片所在的 Node 3 。 </li>
<li>Node 3 从主分片检索文档，修改 _source 字段中的 JSON ，并且尝试重新索引主分片的文档。如果文档已经被另一个进程修改，它会重试步骤 3 ，超过 <strong>retry_on_conflict</strong> 次 后放弃。</li>
<li>如果 Node 3 成功地更新文档，它将新版本的文档并行转发到 Node 1 和 Node 2 上的 副本分片，重新建立索引。一旦所有副本分片都返回成功， Node 3 向协调节点也返回成功，协调节点向客户端返回成功。</li>
</ol>
<blockquote>
<p>​		当主分片把更改转发到副本分片时， 它不会转发更新请求。 相反，它转发完整文档的新版本。请记住， 这些更改将会异步转发到副本分片，并且不能保证它们以发送它们相同的顺序到达。 如果 Elasticsearch 仅 转发更改请求，则可能以错误的顺序应用更改，导致得到损坏的文档。</p>
</blockquote>
<h4 id="4-5-4-多文档操作流"><a href="#4-5-4-多文档操作流" class="headerlink" title="4.5.4 多文档操作流"></a>4.5.4 多文档操作流</h4><p>​		mget 和 bulk API 的模式类似于单文档模式。区别在于协调节点知道每个文档存在于哪个分片中。它将整个多文档请求分解成每个分片的多文档请求，并且将这些请求并行转 发到每个参与节点。</p>
<p>​		协调节点一旦收到来自每个节点的应答，就将每个节点的响应收集整理成单个响应，返回给客户端</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809101927931.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809101927931"></p>
<p><strong>用单个 mget 请求取回多个文档所需的步骤顺序</strong></p>
<ol>
<li>客户端向 Node 1 发送 mget 请求.</li>
<li>Node 1 为每个分片构建多文档获取请求，然后并行转发这些请求到托管在每个所需的主分片或者副本分片的节点上。一旦收到所有答复， Node 1 构建响应并将其返回给客 户端。</li>
</ol>
<p>可以对 docs 数组中每个文档设置 routing 参数。</p>
<p>$\textcolor{blue}{bulk API}$， 允许在单个批量请求中执行多个创建、索引、删除和更新请求。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809102045508.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809102045508"></p>
<p>bulk API 按如下步骤顺序执行： </p>
<ol>
<li>客户端向 Node 1 发送 bulk 请求。 </li>
<li>Node 1 为每个节点创建一个批量请求，并将这些请求并行转发到每个包含主分片的节 点主机。</li>
<li>主分片一个接一个按顺序执行每个操作。当每个操作成功时，主分片并行转发新文档（或 删除）到副本分片，然后执行下一个操作。 一旦所有的副本分片报告所有操作成功， 该节点将向协调节点报告成功，协调节点将这些响应收集整理并返回给客户端。</li>
</ol>
<h3 id="4-6-分片原理"><a href="#4-6-分片原理" class="headerlink" title="4.6 分片原理"></a>4.6 分片原理</h3><p>​		分片是 Elasticsearch 最小的工作单元。但是究竟什么是一个分片，它是如何工作的？ 传统的数据库每个字段存储单个值，但这对全文检索并不够。文本字段中的每个单词需要被搜索，对数据库意味着需要单个字段有索引多值的能力。最好的支持是一个字段多个值 需求的数据结构是倒排索引。</p>
<h4 id="4-6-1-倒排索引"><a href="#4-6-1-倒排索引" class="headerlink" title="4.6.1 倒排索引"></a>4.6.1 倒排索引</h4><p>​		Elasticsearch 使用一种称为<strong>倒排索引</strong>的结构，它适用于快速的全文搜索。 </p>
<p>​		见其名，知其意，有倒排索引，肯定会对应有正向索引。正向索引（forward index）， 反向索引（inverted index）更熟悉的名字是倒排索引。 		所谓的正向索引，就是搜索引擎会将待搜索的文件都对应一个文件 ID，搜索时将这个 ID 和搜索关键字进行对应，形成 K-V 对，然后对关键字进行统计计数</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809102436053.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809102436053"></p>
<p>​		但是互联网上收录在搜索引擎中的文档的数目是个天文数字，这样的索引结构根本无法满足 实时返回排名结果的要求。所以，搜索引擎会将正向索引重新构建为倒排索引，即把文件 ID对应到关键词的映射转换为关键词到文件ID的映射，每个关键词都对应着一系列的文件， 这些文件中都出现这个关键词。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809102511544.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809102511544"></p>
<p>​		一个倒排索引由文档中所有不重复词的列表构成，对于其中每个词，有一个包含它的文档列表。例如，假设我们有两个文档，每个文档的 content 域包含如下内容：</p>
<ul>
<li>The quick brown fox jumped over the lazy dog </li>
<li>Quick brown foxes leap over lazy dogs in summer</li>
</ul>
<p>为了创建倒排索引，我们首先将每个文档的 content 域拆分成单独的 词（我们称它为 <strong>词条 或 tokens</strong> ），创建一个包含所有不重复词条的排序列表，然后列出每个词条出现在哪个文 档。结果如下所示：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809102610755.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809102610755"></p>
<p>现在，如果我们想搜索 <strong>quick brown</strong> ，我们只需要查找包含每个词条的文档</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809102646776.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809102646776"></p>
<p>​		两个文档都匹配，但是第一个文档比第二个匹配度更高。如果我们使用仅计算匹配词条数量 的简单相似性算法，那么我们可以说，对于我们查询的相关性来讲，第一个文档比第二个文 档更佳。</p>
<p>但是，我们目前的倒排索引有一些问题：</p>
<ul>
<li>Quick 和 quick 以独立的词条出现，然而用户可能认为它们是相同的词。 </li>
<li>fox 和 foxes 非常相似, 就像 dog 和 dogs ；他们有相同的词根。</li>
<li>jumped 和 leap, 尽管没有相同的词根，但他们的意思很相近。他们是同义词。</li>
</ul>
<p>使用前面的索引搜索 <strong>+Quick +fox</strong> 不会得到任何匹配文档。（记住，+ 前缀表明这个词必须存在。）只有同时出现 Quick 和 fox 的文档才满足这个查询条件，但是第一个文档包含 quick fox ，第二个文档包含 Quick foxes 。 </p>
<p>我们的用户可以合理的期望两个文档与查询匹配。我们可以做的更好。 如果我们将词条规范为标准模式，那么我们可以找到与用户搜索的词条不完全一致，但具有 足够相关性的文档。例如：</p>
<ul>
<li>Quick 可以小写化为 quick 。 </li>
<li>foxes 可以 词干提取 –变为词根的格式– 为 fox 。类似的， dogs 可以为提取为 dog 。 </li>
<li>jumped 和 leap 是同义词，可以索引为相同的单词 jump 。</li>
</ul>
<p>现在索引看上去像这样：</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809102958114.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809102958114"></p>
<p>​		这还远远不够。我们搜索 +Quick +fox 仍然 会失败，因为在我们的索引中，已经没有 Quick  了。但是，如果我们对搜索的字符串使用与 content 域相同的标准化规则，会变成查询 +quick +fox，这样两个文档都会匹配！分词和标准化的过程称为<strong>分析</strong></p>
<p>​		这非常重要。你只能搜索在索引中出现的词条，所以索引文本和查询字符串必须标准化为相同的格式。</p>
<h4 id="4-6-2-文档搜索"><a href="#4-6-2-文档搜索" class="headerlink" title="4.6.2 文档搜索"></a>4.6.2 文档搜索</h4><p>​		早期的全文检索会为整个文档集合建立一个很大的倒排索引并将其写入到磁盘。 一旦新的索引就绪，旧的就会被其替换，这样最近的变化便可以被检索到。 		倒排索引被写入磁盘后是 可改变的:它永远不会修改。 </p>
<p>​		不变性有重要的价值：</p>
<ul>
<li>不需要锁。如果你从来不更新索引，你就不需要担心多进程同时修改数据的问题。 </li>
<li>一旦索引被读入内核的文件系统缓存，便会留在哪里，由于其不变性。只要文件系统缓存中还有足够 的空间，那么大部分读请求会直接请求内存，而不会命中磁盘。这提供了很大的性能提升。</li>
<li>其它缓存(像 filter 缓存)，在索引的生命周期内始终有效。它们不需要在每次数据改变时被重建，因为数据不会变化。 </li>
<li>写入单个大的倒排索引允许数据被压缩，减少磁盘 I&#x2F;O 和 需要被缓存到内存的索引的使用量。 当然，一个不变的索引也有不好的地方。主要事实是它是不可变的! 你不能修改它。如果你需要让一个新的文档可被搜索，你需要重建整个索引。这要么对一个索引所能包含的数据量造成了很大的限制，要么对索引可被更新的频率造成了很大的限制。</li>
</ul>
<h4 id="4-6-3-动态更新索引"><a href="#4-6-3-动态更新索引" class="headerlink" title="4.6.3 动态更新索引"></a>4.6.3 动态更新索引</h4><blockquote>
<p>如何在保留不变性的前提下实现倒排索引的更新？</p>
</blockquote>
<p>​		答案是: 用更多的索引。通过增加新的补充索引来反映新近的修改，而不是直接重写整个倒排索引。每一个倒排索引都会被轮流查询到，从最早的开始查询完后再对结果进行合并。 </p>
<p>​		Elasticsearch 基于 Lucene, 这个 java 库引入了按段搜索的概念。 每一 段 本身都是一 个倒排索引， 但索引在 Lucene 中除表示所有段的集合外， 还增加了提交点的概念 — 一 个列出了所有已知段的文件</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809103419762.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809103419762"></p>
<p><strong>按段搜索</strong>会以如下流程执行：</p>
<ol>
<li><p>新文档被收集到内存索引缓存</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809103632667.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809103632667"></p>
</li>
<li><p>不时地, 缓存被提交</p>
<p>(1) 一个新的段—一个追加的倒排索引—被写入磁盘。</p>
<p>(2) 一个新的包含新段名字的 提交点 被写入磁盘 </p>
<p>(3) 磁盘进行 同步 — 所有在文件系统缓存中等待的写入都刷新到磁盘，以确保它们被写入物理文件</p>
</li>
<li><p>新的段被开启，让它包含的文档可见以被搜索</p>
</li>
<li><p>内存缓存被清空，等待接收新的文档</p>
</li>
</ol>
<p><img src="/blog/ElasticSearch.assets/image-20220809103844003.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809103844003"></p>
<p>​		当一个查询被触发，所有已知的段按顺序被查询。词项统计会对所有段的结果进行聚合，以保证每个词和每个文档的关联都被准确计算。 这种方式可以用相对较低的成本将新文档添加到索引。 </p>
<p>​		段是不可改变的，所以既不能从把文档从旧的段中移除，也不能修改旧的段来进行反映文档 的更新。 取而代之的是，每个提交点会包含一个 .del 文件，文件中会列出这些被删除文档 的段信息。 </p>
<p>​		当一个文档被 “删除” 时，它实际上只是在 .del 文件中被 标记 删除。一个被标记删除的文档仍然可以被查询匹配到， 但它会在最终结果被返回前从结果集中移除。 </p>
<p>​		文档更新也是类似的操作方式：当一个文档被更新时，旧版本文档被标记删除，文档的新版 本被索引到一个新的段中。 可能两个版本的文档都会被一个查询匹配到，但被删除的那个 旧版本文档在结果集返回前就已经被移除。</p>
<h4 id="4-6-4-近实时搜索"><a href="#4-6-4-近实时搜索" class="headerlink" title="4.6.4 近实时搜索"></a>4.6.4 近实时搜索</h4><p>​		随着按段（per-segment）搜索的发展，一个新的文档从索引到可被搜索的延迟显著降低 了。新文档在几分钟之内即可被检索，但这样还是不够快。磁盘在这里成为了瓶颈。提交 （Commiting）一个新的段到磁盘需要一个 fsync 来确保段被物理性地写入磁盘，这样在断电的时候就不会丢失数据。 但是 fsync 操作代价很大; 如果每次索引一个文档都去执行一 次的话会造成很大的性能问题。 </p>
<p>​		我们需要的是一个更轻量的方式来使一个文档可被搜索，这意味着 fsync 要从整个过程中 被移除。在 Elasticsearch 和磁盘之间是文件系统缓存。 像之前描述的一样，在内存索引缓冲区中的文档会被写入到一个新的段中。 但是这里新段会被先写入到文件系统缓存—这一 步代价会比较低，稍后再被刷新到磁盘—这一步代价比较高。不过只要文件已经在缓存中， 就可以像其它文件一样被打开和读取了。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809104347686.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809104347686"></p>
<p>​		Lucene 允许新段被写入和打开—使其包含的文档在未进行一次完整提交时便对搜索可见。 这种方式比进行一次提交代价要小得多，并且在不影响性能的前提下可以被频繁地执行。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809104416907.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809104416907"></p>
<p>​		在 Elasticsearch 中，写入和打开一个新段的轻量的过程叫做 refresh 。 默认情况下每个分片会每秒自动刷新一次。这就是为什么我们说 Elasticsearch 是 近实时搜索: 文档的变化并不是立即对搜索可见，但会在一秒之内变为可见。 这些行为可能会对新用户造成困惑: 他们索引了一个文档然后尝试搜索它，但却没有搜到。 这个问题的解决办法是用 refresh API 执行一次手动刷新: &#x2F;users&#x2F;_refresh</p>
<blockquote>
<p>尽管刷新是比提交轻量很多的操作，它还是会有性能开销。当写测试的时候， 手动刷新很有用，但是不要 在生产环境下每次索引一个文档都去手动刷新。 相反，你的应用需要意识到 Elasticsearch 的近实时的性质，并接受它的不足。</p>
</blockquote>
<p>​		并不是所有的情况都需要每秒刷新。可能你正在使用 Elasticsearch 索引大量的日志文件， 你可能想优化索引速度而不是近实时搜索， 可以通过设置 refresh_interval ， 降低每个索 引的刷新频率</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;settings&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;refresh_interval&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;30s&quot;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p>​		refresh_interval 可以在既存索引上进行动态更新。 在生产环境中，当你正在建立一个大的新索引时，可以先关闭自动刷新，待开始使用该索引时，再把它们调回来</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs text"># 关闭自动刷新<br>PUT /users/_settings<br>&#123; &quot;refresh_interval&quot;: -1 &#125; <br># 每一秒刷新<br>PUT /users/_settings<br>&#123; &quot;refresh_interval&quot;: &quot;1s&quot; &#125;<br></code></pre></td></tr></table></figure>

<h4 id="4-6-5-持久化变更"><a href="#4-6-5-持久化变更" class="headerlink" title="4.6.5 持久化变更"></a>4.6.5 持久化变更</h4><p>​		如果没有用 fsync 把数据从文件系统缓存刷（flush）到硬盘，我们不能保证数据在断电甚至是程序正常退出之后依然存在。为了保证 Elasticsearch 的可靠性，需要确保数据变 化被持久化到磁盘。在 动态更新索引，我们说一次完整的提交会将段刷到磁盘，并写入一个包含所有段列表的提交点。Elasticsearch 在启动或重新打开一个索引的过程中使用这个提 交点来判断哪些段隶属于当前分片。</p>
<p>​		即使通过每秒刷新（refresh）实现了近实时搜索，我们仍然需要经常进行完整提交来确 保能从失败中恢复。但在两次提交之间发生变化的文档怎么办？我们也不希望丢失掉这些数 据。Elasticsearch 增加了一个 translog ，或者叫事务日志，在每一次对 Elasticsearch 进行 操作时均进行了日志记录</p>
<p>整个流程如下：</p>
<ol>
<li><p>一个文档被索引之后，就会被添加到内存缓冲区，并且追加到了 translog</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809105250522.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809105250522"></p>
</li>
<li><p>刷新（refresh）使分片每秒被刷新（refresh）一次：</p>
<ul>
<li>这些在内存缓冲区的文档被写入到一个新的段中，且没有进行 fsync 操作。 </li>
<li>这个段被打开，使其可被搜索 </li>
<li>内存缓冲区被清空</li>
</ul>
<p><img src="/blog/ElasticSearch.assets/image-20220809105413424.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809105413424"></p>
</li>
<li><p>这个进程继续工作，更多的文档被添加到内存缓冲区和追加到事务日志</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809105627003.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809105627003"></p>
</li>
<li><p>每隔一段时间—例如 translog 变得越来越大—索引被刷新（flush）；一个新的 translog  被创建，并且一个全量提交被执行</p>
<ul>
<li>所有在内存缓冲区的文档都被写入一个新的段。</li>
<li>缓冲区被清空。</li>
<li>一个提交点被写入硬盘。</li>
<li>文件系统缓存通过 fsync 被刷新（flush）。</li>
<li>老的 translog 被删除。</li>
</ul>
</li>
</ol>
<p>​		translog 提供所有还没有被刷到磁盘的操作的一个持久化纪录。当 Elasticsearch 启动的时候， 它会从磁盘中使用最后一个提交点去恢复已知的段，并且会重放 translog 中所有在最后一次提交后发生的变更操作。</p>
<p>​		 translog 也被用来提供实时 CRUD 。当你试着通过 ID 查询、更新、删除一个文档，它会在尝试从相应的段中检索之前， 首先检查 translog 任何最近的变更。这意味着它总是能够 实时地获取到文档的最新版本。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809105807503.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809105807503"></p>
<p>执行一个提交并且截断 translog 的行为在 Elasticsearch 被称作一次 flush</p>
<p> 分片每 30 分钟被自动刷新（flush），或者在 translog 太大的时候也会刷新</p>
<p>​		你很少需要自己手动执行 flush 操作；通常情况下，自动刷新就足够了。这就是说，在重启节点或关闭索引之前执行 flush 有益于你的索引。当 Elasticsearch 尝试恢复或重新打 开一个索引， 它需要重放 translog 中所有的操作，所以如果日志越短，恢复越快。 </p>
<p>​		translog 的目的是保证操作不会丢失，在文件被 fsync 到磁盘前，被写入的文件在重启之后就会丢失。默认 translog 是每 5 秒被 fsync 刷新到硬盘， 或者在每次写请求完成之后执行(e.g. index, delete, update, bulk)。这个过程在主分片和复制分片都会发生。最终， 基本上，这意味着在整个请求被 fsync 到主分片和复制分片的 translog 之前，你的客户端不会得到一个 200 OK 响应。 </p>
<p>​		在每次请求后都执行一个 fsync 会带来一些性能损失，尽管实践表明这种损失相对较 小（特别是 bulk 导入，它在一次请求中平摊了大量文档的开销）。 </p>
<p>​		但是对于一些大容量的偶尔丢失几秒数据问题也并不严重的集群，使用异步的 fsync  还是比较有益的。比如，写入的数据被缓存到内存中，再每 5 秒执行一次 fsync 。如果你决定使用异步 translog 的话，你需要保证在发生 crash 时，丢失掉 sync_interval 时间段 的数据也无所谓。请在决定前知晓这个特性。如果你不确定这个行为的后果，最好是使用默 认的参数（ “index.translog.durability”: “request” ）来避免数据丢失。</p>
<h4 id="4-6-6-段合并"><a href="#4-6-6-段合并" class="headerlink" title="4.6.6 段合并"></a>4.6.6 段合并</h4><p>​		由于自动刷新流程每秒会创建一个新的段 ，这样会导致短时间内的段数量暴增。而段数目太多会带来较大的麻烦。 每一个段都会消耗文件句柄、内存和 cpu 运行周期。更重要的是，每个搜索请求都必须轮流检查每个段；所以段越多，搜索也就越慢。 </p>
<p>​		Elasticsearch 通过在后台进行段合并来解决这个问题。小的段被合并到大的段，然后这些大的段再被合并到更大的段。 段合并的时候会将那些旧的已删除文档从文件系统中清除。被删除的文档（或被更新文档的 旧版本）不会被拷贝到新的大段中。 </p>
<p>​		启动段合并不需要你做任何事。进行索引和搜索时会自动进行。</p>
<ol>
<li><p>当索引的时候，刷新（refresh）操作会创建新的段并将段打开以供搜索使用。</p>
</li>
<li><p>合并进程选择一小部分大小相似的段，并且在后台将它们合并到更大的段中。这并不会 中断索引和搜索</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809110325362.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809110325362"></p>
</li>
<li><p>一旦合并结束，老的段被删除</p>
<ul>
<li>新的段被刷新（flush）到了磁盘。 ** 写入一个包含新段且排除旧的和较小的段 的新提交点。</li>
<li>新的段被打开用来搜索。</li>
<li>老的段被删除。</li>
</ul>
</li>
</ol>
<p><img src="/blog/ElasticSearch.assets/image-20220809110403786.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809110403786"></p>
<p>合并大的段需要消耗大量的 I&#x2F;O 和 CPU 资源，如果任其发展会影响搜索性能。Elasticsearch 在默认情况下会对合并流程进行资源限制，所以搜索仍然有足够的资源很好地执行。</p>
<h3 id="4-7-文档分析"><a href="#4-7-文档分析" class="headerlink" title="4.7 文档分析"></a>4.7 文档分析</h3><p>分析 包含下面的过程：</p>
<ul>
<li><p>将一块文本分成适合于倒排索引的独立的词条 </p>
</li>
<li><p>将这些词条统一化为标准格式以提高它们的“可搜索性”，或者 recall 分析器执行上面的工作。分析器实际上是将三个功能封装到了一个包里：</p>
<ul>
<li><p>字符过滤器</p>
<p>​		首先，字符串按顺序通过每个字符过滤器 。他们的任务是在分词前整理字符串。一个字符过滤器可以用来去掉 HTML，或者将 &amp; 转化成 and。</p>
</li>
<li><p>分词器</p>
<p>​		其次，字符串被分词器分为单个的词条。一个简单的分词器遇到空格和标点的时候， 可能会将文本拆分成词条。</p>
</li>
<li><p>Token过滤器</p>
<p>​		最后，词条按顺序通过每个 token 过滤器 。这个过程可能会改变词条（例如，小写化 Quick ），删除词条（例如， 像 a， and， the 等无用词），或者增加词条（例如，像 jump  和 leap 这种同义词）。</p>
</li>
</ul>
</li>
</ul>
<h4 id="4-7-1-内置分析器"><a href="#4-7-1-内置分析器" class="headerlink" title="4.7.1 内置分析器"></a>4.7.1 内置分析器</h4><p>​		Elasticsearch 还附带了可以直接使用的预包装的分析器。接下来我们会列出最重要的分析器。为了证明它们的差异，我们看看每个分析器会从下面的字符串得到哪些词条： </p>
<p>​		“Set the shape to semi-transparent by calling set_trans(5)”</p>
<ul>
<li><p>标准分析器</p>
<p>​		标准分析器是 Elasticsearch 默认使用的分析器。它是分析各种语言文本最常用的选择。 它根据 Unicode 联盟 定义的 单词边界 划分文本。删除绝大部分标点。最后，将词条小写。 它会产生： set, the, shape, to, semi, transparent, by, calling, set_trans, 5</p>
</li>
<li><p>简单分析器</p>
<p>​		简单分析器在任何不是字母的地方分隔文本，将词条小写。它会产生： set, the, shape, to, semi, transparent, by, calling, set, trans</p>
</li>
<li><p>空格分析器</p>
<p>​		空格分析器在空格的地方划分文本。它会产生： </p>
<p>Set, the, shape, to, semi-transparent, by, calling, set_trans(5)</p>
</li>
<li><p>语言分析器</p>
<p>​		特定语言分析器可用于 很多语言。它们可以考虑指定语言的特点。例如， 英语 分析 器附带了一组英语无用词（常用单词，例如 and 或者 the ，它们对相关性没有多少影响）， 它们会被删除。 由于理解英语语法的规则，这个分词器可以提取英语单词的 词干 。</p>
<p>英语 分词器会产生下面的词条：</p>
<p> set, shape, semi, transpar, call, set_tran, 5 </p>
<p>注意看 transparent、 calling 和 set_trans 已经变为词根格式</p>
</li>
</ul>
<h4 id="4-7-2-分析器使用场景"><a href="#4-7-2-分析器使用场景" class="headerlink" title="4.7.2 分析器使用场景"></a>4.7.2 分析器使用场景</h4><p>​		当我们 索引 一个文档，它的全文域被分析成词条以用来创建倒排索引。 但是，当我 们在全文域 搜索 的时候，我们需要将查询字符串通过 相同的分析过程 ，以保证我们搜索 的词条格式与索引中的词条格式一致。</p>
<p>​		全文查询，理解每个域是如何定义的，因此它们可以做正确的事：</p>
<ul>
<li>当你查询一个 全文 域时， 会对查询字符串应用相同的分析器，以产生正确的搜索词条列表。 </li>
<li>当你查询一个 精确值 域时，不会分析查询字符串，而是搜索你指定的精确值。</li>
</ul>
<h4 id="4-7-3-测试分析器"><a href="#4-7-3-测试分析器" class="headerlink" title="4.7.3 测试分析器"></a>4.7.3 测试分析器</h4><p>​		有些时候很难理解分词的过程和实际被存储到索引中的词条，特别是你刚接触 Elasticsearch。为了理解发生了什么，你可以使用 analyze API 来看文本是如何被分析的。 在消息体里，指定分析器和要分析的文本</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs json">#GET http<span class="hljs-punctuation">:</span><span class="hljs-comment">//localhost:9200/_analyze</span><br><span class="hljs-punctuation">&#123;</span><br>  <span class="hljs-attr">&quot;analyzer&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;standard&quot;</span><span class="hljs-punctuation">,</span><br>  <span class="hljs-attr">&quot;text&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;Text to analyze&quot;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p>结果中每个元素代表一个单独的词条：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;tokens&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;text&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;ALPHANUM&gt;&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><br>		<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;to&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">7</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;ALPHANUM&gt;&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><br>		<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;analyze&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">8</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">15</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;ALPHANUM&gt;&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">]</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p>token 是实际存储到索引中的词条。 position 指明词条在原始文本中出现的位置。 start_offset 和 end_offset 指明字符在原始字符串中的位置。</p>
<h4 id="4-7-4-指定分析器"><a href="#4-7-4-指定分析器" class="headerlink" title="4.7.4 指定分析器"></a>4.7.4 指定分析器</h4><p>​		当Elasticsearch在你的文档中检测到一个新的字符串域，它会自动设置其为一个全文 字 符串 域，使用 标准 分析器对它进行分析。你不希望总是这样。可能你想使用一个不同的 分析器，适用于你的数据使用的语言。有时候你想要一个字符串域就是一个字符串域—不使用分析，直接索引你传入的精确值，例如用户 ID 或者一个内部的状态域或标签。要做到这 一点，我们必须手动指定这些域的映射。</p>
<h4 id="4-7-5-IK-分词器"><a href="#4-7-5-IK-分词器" class="headerlink" title="4.7.5 IK 分词器"></a>4.7.5 IK 分词器</h4><p>首先我们通过 Postman 发送 GET 请求查询分词效果</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs json"># GET http<span class="hljs-punctuation">:</span><span class="hljs-comment">//localhost:9200/_analyze</span><br><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;text&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;测试单词&quot;</span><br><span class="hljs-punctuation">&#125;</span><br><br></code></pre></td></tr></table></figure>

<p><img src="/blog/ElasticSearch.assets/image-20220809111602659.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809111602659"></p>
<p>ES 的默认分词器无法识别中文中测试、单词这样的词汇，而是简单的将每个字拆完分为一 个词</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;tokens&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>        <span class="hljs-punctuation">&#123;</span><br>            <span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;测&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;IDEOGRAPHIC&gt;&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br>        <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-punctuation">&#123;</span><br>            <span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;试&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;IDEOGRAPHIC&gt;&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><br>        <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-punctuation">&#123;</span><br>            <span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;单&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;IDEOGRAPHIC&gt;&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><br>        <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-punctuation">&#123;</span><br>            <span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;词&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;IDEOGRAPHIC&gt;&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><br>        <span class="hljs-punctuation">&#125;</span><br>    <span class="hljs-punctuation">]</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p>这样的结果显然不符合我们的使用要求，所以我们需要下载 ES 对应版本的中文分词器。</p>
<p>我们这里采用 IK 中文分词器，下载地址为: </p>
<p> <a target="_blank" rel="noopener" href="https://github.com/medcl/elasticsearch-analysis-ik/releases/tag/v7.8.0">https://github.com/medcl/elasticsearch-analysis-ik/releases/tag/v7.8.0</a> </p>
<p>将解压后的后的文件夹放入 ES 根目录下的 plugins 目录下，重启 ES 即可使用。 这次加入新的查询参数”analyzer”:”ik_max_word”</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;text&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;测试单词&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;analyzer&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;ik_max_word&quot;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<ul>
<li>ik_max_word：会将文本做最细粒度的拆分</li>
<li>ik_smart：会将文本做最粗粒度的拆分</li>
</ul>
<p><img src="/blog/ElasticSearch.assets/image-20220809111846684.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809111846684"></p>
<p>使用中文分词后的结果为：</p>
<figure class="highlight prolog"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs prolog">&#123;<br>    <span class="hljs-string">&quot;tokens&quot;</span>: [<br>        &#123;<br>            <span class="hljs-string">&quot;token&quot;</span>: <span class="hljs-string">&quot;测试&quot;</span>,<br>            <span class="hljs-string">&quot;start_offset&quot;</span>: <span class="hljs-number">0</span>,<br>            <span class="hljs-string">&quot;end_offset&quot;</span>: <span class="hljs-number">2</span>,<br>            <span class="hljs-string">&quot;type&quot;</span>: <span class="hljs-string">&quot;CN_WORD&quot;</span>,<br>            <span class="hljs-string">&quot;position&quot;</span>: <span class="hljs-number">0</span><br>        &#125;,<br>        &#123;<br>            <span class="hljs-string">&quot;token&quot;</span>: <span class="hljs-string">&quot;单词&quot;</span>,<br>            <span class="hljs-string">&quot;start_offset&quot;</span>: <span class="hljs-number">2</span>,<br>            <span class="hljs-string">&quot;end_offset&quot;</span>: <span class="hljs-number">4</span>,<br>            <span class="hljs-string">&quot;type&quot;</span>: <span class="hljs-string">&quot;CN_WORD&quot;</span>,<br>            <span class="hljs-string">&quot;position&quot;</span>: <span class="hljs-number">1</span><br>        &#125;<br>    ]<br>&#125;<br></code></pre></td></tr></table></figure>

<p>ES 中也可以进行扩展词汇，首先查询</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;text&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;弗雷尔卓德&quot;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;analyzer&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;ik_max_word&quot;</span><br><span class="hljs-punctuation">&#125;</span><br><br></code></pre></td></tr></table></figure>

<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;tokens&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;弗&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;CN_CHAR&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><br>		<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;雷&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;CN_CHAR&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><br>		<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;尔&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;CN_CHAR&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><br>		<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;卓&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;CN_CHAR&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><br>		<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;德&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;CN_CHAR&quot;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">]</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p>首先进入 ES 根目录中的 plugins 文件夹下的 ik 文件夹，进入 config 目录，创建 custom.dic 文件，写入弗雷尔卓德。同时打开 IKAnalyzer.cfg.xml 文件，将新建的 custom.dic 配置其中， 重启 ES 服务器。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809112044584.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809112044584"></p>
<p><img src="/blog/ElasticSearch.assets/image-20220809112108355.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809112108355"></p>
<h4 id="4-7-6-自定义分析器"><a href="#4-7-6-自定义分析器" class="headerlink" title="4.7.6 自定义分析器"></a>4.7.6 自定义分析器</h4><p>​		虽然 Elasticsearch 带有一些现成的分析器，然而在分析器上 Elasticsearch 真正的强大之 处在于，你可以通过在一个适合你的特定数据的设置之中组合字符过滤器、分词器、词汇单 元过滤器来创建自定义的分析器。在 分析与分析器 我们说过，一个 分析器 就是在一个包 里面组合了三种函数的一个包装器， 三种函数按照顺序被执行:</p>
<ul>
<li><p>字符过滤器</p>
<p>字符过滤器 用来 整理 一个尚未被分词的字符串。例如，如果我们的文本是 HTML 格 式的，它会包含像 </p><p> 或者 <div> 这样的 HTML 标签，这些标签是我们不想索引的。我 们可以使用 html 清除 字符过滤器 来移除掉所有的 HTML 标签，并且像把 &amp;Aacute 转换 为相对应的 Unicode 字符 Á 这样，转换 HTML 实体。一个分析器可能有 0 个或者多个字符 过滤器。</div></p>
</li>
<li><p>分词器</p>
<p>​		一个分析器 必须 有一个唯一的分词器。 分词器把字符串分解成单个词条或者词汇单 元。 标准 分析器里使用的 标准 分词器 把一个字符串根据单词边界分解成单个词条，并 且移除掉大部分的标点符号，然而还有其他不同行为的分词器存在。 </p>
<p>例如， 关键词 分词器 完整地输出 接收到的同样的字符串，并不做任何分词。 空格 分词 器 只根据空格分割文本 。 正则 分词器 根据匹配正则表达式来分割文本 。</p>
</li>
<li><p>词单元过滤器</p>
<p>​		经过分词，作为结果的 词单元流 会按照指定的顺序通过指定的词单元过滤器 。 词单元过滤器可以修改、添加或者移除词单元。我们已经提到过 lowercase 和 stop 词过滤 器 ，但是在 Elasticsearch 里面还有很多可供选择的词单元过滤器。词干过滤器 把单词 遏 制 为 词干。 ascii_folding 过滤器移除变音符，把一个像 “très” 这样的词转换为 “tres” 。ngram 和 edge_ngram 词单元过滤器 可以产生 适合用于部分匹配或者自动补全的词单元。 接下来，我们看看如何创建自定义的分析器：</p>
</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;settings&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;analysis&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>			<span class="hljs-attr">&quot;char_filter&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;&amp;_to_and&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>					<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;mapping&quot;</span><span class="hljs-punctuation">,</span><br>					<span class="hljs-attr">&quot;mappings&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>						<span class="hljs-string">&quot;&amp;=&gt; and &quot;</span><br>					<span class="hljs-punctuation">]</span><br>				<span class="hljs-punctuation">&#125;</span><br>			<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;filter&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;my_stopwords&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>					<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;stop&quot;</span><span class="hljs-punctuation">,</span><br>					<span class="hljs-attr">&quot;stopwords&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>						<span class="hljs-string">&quot;the&quot;</span><span class="hljs-punctuation">,</span><br>						<span class="hljs-string">&quot;a&quot;</span><br>					<span class="hljs-punctuation">]</span><br>				<span class="hljs-punctuation">&#125;</span><br>			<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>			<span class="hljs-attr">&quot;analyzer&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;my_analyzer&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>					<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;custom&quot;</span><span class="hljs-punctuation">,</span><br>					<span class="hljs-attr">&quot;char_filter&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>						<span class="hljs-string">&quot;html_strip&quot;</span><span class="hljs-punctuation">,</span><br>						<span class="hljs-string">&quot;&amp;_to_and&quot;</span><br>					<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span><br>					<span class="hljs-attr">&quot;tokenizer&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;standard&quot;</span><span class="hljs-punctuation">,</span><br>					<span class="hljs-attr">&quot;filter&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>						<span class="hljs-string">&quot;lowercase&quot;</span><span class="hljs-punctuation">,</span><br>						<span class="hljs-string">&quot;my_stopwords&quot;</span><br>					<span class="hljs-punctuation">]</span><br>				<span class="hljs-punctuation">&#125;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">&#125;</span><br>	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p>索引被创建以后，使用 analyze API 来 测试这个新的分析器</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>  <span class="hljs-attr">&quot;text&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;The quick &amp; brown fox&quot;</span><span class="hljs-punctuation">,</span><br>  <span class="hljs-attr">&quot;analyzer&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;my_analyzer&quot;</span><br><span class="hljs-punctuation">&#125;</span><br><br></code></pre></td></tr></table></figure>

<p>下面的缩略结果展示出我们的分析器正在正确地运行</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;tokens&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>        <span class="hljs-punctuation">&#123;</span><br>            <span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;quick&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">9</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;ALPHANUM&gt;&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><br>        <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-punctuation">&#123;</span><br>            <span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;and&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">10</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">11</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;ALPHANUM&gt;&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><br>        <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-punctuation">&#123;</span><br>            <span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;brown&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">12</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">17</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;ALPHANUM&gt;&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><br>        <span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-punctuation">&#123;</span><br>            <span class="hljs-attr">&quot;token&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;fox&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;start_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">18</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;end_offset&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">21</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;&lt;ALPHANUM&gt;&quot;</span><span class="hljs-punctuation">,</span><br>            <span class="hljs-attr">&quot;position&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4</span><br>        <span class="hljs-punctuation">&#125;</span><br>    <span class="hljs-punctuation">]</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h3 id="4-8-文档处理"><a href="#4-8-文档处理" class="headerlink" title="4.8 文档处理"></a>4.8 文档处理</h3><h4 id="4-8-1-文档冲突"><a href="#4-8-1-文档冲突" class="headerlink" title="4.8.1 文档冲突"></a>4.8.1 文档冲突</h4><p>​		当我们使用 index API 更新文档 ，可以一次性读取原始文档，做我们的修改，然后重 新索引 整个文档 。 最近的索引请求将获胜：无论最后哪一个文档被索引，都将被唯一存 储在 Elasticsearch 中。如果其他人同时更改这个文档，他们的更改将丢失。 </p>
<p>​		很多时候这是没有问题的。也许我们的主数据存储是一个关系型数据库，我们只是将数 据复制到 Elasticsearch 中并使其可被搜索。 也许两个人同时更改相同的文档的几率很小。 或者对于我们的业务来说偶尔丢失更改并不是很严重的问题。</p>
<p>​		但有时丢失了一个变更就是 非常严重的 。试想我们使用 Elasticsearch 存储我们网上 商城商品库存的数量， 每次我们卖一个商品的时候，我们在 Elasticsearch 中将库存数量减 少。有一天，管理层决定做一次促销。突然地，我们一秒要卖好几个商品。 假设有两个 web  程序并行运行，每一个都同时处理所有商品的销售</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809132022009.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809132022009"></p>
<p>​		web_1 对 stock_count 所做的更改已经丢失，因为 web_2 不知道它的 stock_count 的 拷贝已经过期。 结果我们会认为有超过商品的实际数量的库存，因为卖给顾客的库存商品并不存在，我们将让他们非常失望。</p>
<p>​		变更越频繁，读数据和更新数据的间隙越长，也就越可能丢失变更。 </p>
<p>​		在数据库领域中，有两种方法通常被用来确保并发更新时变更不会丢失：</p>
<ul>
<li><p>悲观控制并发</p>
<p>​		这种方法被关系型数据库广泛使用，它假定有变更冲突可能发生，因此阻塞访问资源以 防止冲突。 一个典型的例子是读取一行数据之前先将其锁住，确保只有放置锁的线程能够 对这行数据进行修改。</p>
</li>
<li><p>乐观控制并发</p>
<p>​		Elasticsearch 中使用的这种方法假定冲突是不可能发生的，并且不会阻塞正在尝试的操作。 然而，如果源数据在读写当中被修改，更新将会失败。应用程序接下来将决定该如何 解决冲突。 例如，可以重试更新、使用新的数据、或者将相关情况报告给用户。</p>
</li>
</ul>
<h4 id="4-8-2-乐观并发控制"><a href="#4-8-2-乐观并发控制" class="headerlink" title="4.8.2 乐观并发控制"></a>4.8.2 乐观并发控制</h4><p>​		Elasticsearch 是分布式的。当文档创建、更新或删除时， 新版本的文档必须复制到集群中的其他节点。Elasticsearch 也是异步和并发的，这意味着这些复制请求被并行发送，并且到达目的地时也许 顺序是乱的 。 Elasticsearch 需要一种方法确保文档的旧版本不会覆盖新的版本。 </p>
<p>​		当我们之前讨论 index ，GET 和 delete 请求时，我们指出每个文档都有一个 _version  （版本）号，当文档被修改时版本号递增。 Elasticsearch 使用这个 version 号来确保变更以正确顺序得到执行。如果旧版本的文档在新版本之后到达，它可以被简单的忽略。</p>
<p>​		 我们可以利用 version 号来确保 应用中相互冲突的变更不会导致数据丢失。我们通过 指定想要修改文档的 version 号来达到这个目的。 如果该版本不是当前版本号，我们的请求将会失败。</p>
<p>​		 老的版本 es 使用 version，但是新版本不支持了，会报下面的错误，提示我们用 if_seq_no 和 if_primary_term</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>	<span class="hljs-attr">&quot;error&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>		<span class="hljs-attr">&quot;root_cause&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><br>			<span class="hljs-punctuation">&#123;</span><br>				<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;action_request_validation_exception&quot;</span><span class="hljs-punctuation">,</span><br>				<span class="hljs-attr">&quot;reason&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;Validation Failed: 1: internal versioning can not be used for optimistic concurrency control. Please use `if_seq_no` and `if_primary_term` instead;&quot;</span><br>			<span class="hljs-punctuation">&#125;</span><br>		<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-attr">&quot;type&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;action_request_validation_exception&quot;</span><span class="hljs-punctuation">,</span><br>		<span class="hljs-attr">&quot;reason&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;Validation Failed: 1: internal versioning can not be used for optimistic concurrency control. Please use `if_seq_no` and `if_primary_term` instead;&quot;</span><br>	<span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br>	<span class="hljs-attr">&quot;status&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">400</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h4 id="4-8-3-外部系统版本控制"><a href="#4-8-3-外部系统版本控制" class="headerlink" title="4.8.3 外部系统版本控制"></a>4.8.3 外部系统版本控制</h4><p>​		一个常见的设置是使用其它数据库作为主要的数据存储，使用 Elasticsearch 做数据检索， 这意味着主数据库的所有更改发生时都需要被复制到 Elasticsearch ，如果多个进程负责这一数据同步，你可能遇到类似于之前描述的并发问题。 </p>
<p>​		如果你的主数据库已经有了版本号 — 或一个能作为版本号的字段值比如 timestamp — 那么你就可以在 Elasticsearch 中通过增加 version_type&#x3D;external 到查询字符串的方式重用 这些相同的版本号， 版本号必须是大于零的整数， 且小于 9.2E+18 — 一个 Java 中 long  类型的正值。 </p>
<p>​		外部版本号的处理方式和我们之前讨论的内部版本号的处理方式有些不同， Elasticsearch 不是检查当前 _version 和请求中指定的版本号是否相同， 而是检查当前 _version 是否 小于 指定的版本号。 如果请求成功，外部的版本号作为文档的新 _version  进行存储。</p>
<p><img src="/blog/ElasticSearch.assets/image-20220809133038016.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809133038016"></p>
<p><img src="/blog/ElasticSearch.assets/image-20220809133048023.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809133048023"></p>
<p>​		外部版本号不仅在索引和删除请求是可以指定，而且在 创建 新文档时也可以指定。</p>
<h3 id="4-5-Kibana"><a href="#4-5-Kibana" class="headerlink" title="4.5 Kibana"></a>4.5 Kibana</h3><p>​		Kibana 是一个免费且开放的用户界面，能够让你对 Elasticsearch 数据进行可视化，并 让你在 Elastic Stack 中进行导航。你可以进行各种操作，从跟踪查询负载，到理解请求如 何流经你的整个应用，都能轻松完成。 </p>
<p>​		下载地址：<a target="_blank" rel="noopener" href="https://artifacts.elastic.co/downloads/kibana/kibana-7.8.0-windows-x86_64.zip">https://artifacts.elastic.co/downloads/kibana/kibana-7.8.0-windows-x86_64.zip</a></p>
<ol>
<li><p>解压缩下载的 zip 文件 </p>
</li>
<li><p>修改 config&#x2F;kibana.yml 文件</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs yaml"><span class="hljs-comment"># 默认端口</span><br><span class="hljs-attr">server.port:</span> <span class="hljs-number">5601</span><br><span class="hljs-comment"># ES 服务器的地址</span><br><span class="hljs-attr">elasticsearch.hosts:</span> [<span class="hljs-string">&quot;http://localhost:9200&quot;</span>]<br><span class="hljs-comment"># 索引名</span><br><span class="hljs-attr">kibana.index:</span> <span class="hljs-string">&quot;.kibana&quot;</span><br><span class="hljs-comment"># 支持中文</span><br><span class="hljs-attr">i18n.locale:</span> <span class="hljs-string">&quot;zh-CN&quot;</span><br></code></pre></td></tr></table></figure>
</li>
<li><p>Windows 环境下执行 bin&#x2F;kibana.bat 文件</p>
</li>
<li><p>通过浏览器访问 : <a target="_blank" rel="noopener" href="http://localhost:5601/">http://localhost:5601</a></p>
</li>
</ol>
<p><img src="/blog/ElasticSearch.assets/image-20220809134115915.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809134115915"></p>
<h2 id="第5章-Elasticsearch-集成"><a href="#第5章-Elasticsearch-集成" class="headerlink" title="第5章 Elasticsearch 集成"></a>第5章 Elasticsearch 集成</h2><h3 id="5-1-Spring-Data-框架集成"><a href="#5-1-Spring-Data-框架集成" class="headerlink" title="5.1 Spring Data 框架集成"></a>5.1 Spring Data 框架集成</h3><h4 id="5-1-1-Spring-Data-框架介绍"><a href="#5-1-1-Spring-Data-框架介绍" class="headerlink" title="5.1.1 Spring Data 框架介绍"></a>5.1.1 Spring Data 框架介绍</h4><p>​		Spring Data 是一个用于简化数据库、非关系型数据库、索引库访问，并支持云服务的 开源框架。其主要目标是使得对数据的访问变得方便快捷，并支持 map-reduce 框架和云计 算数据服务。 Spring Data 可以极大的简化 JPA（Elasticsearch„）的写法，可以在几乎不用 写实现的情况下，实现对数据的访问和操作。除了 CRUD 外，还包括如分页、排序等一些 常用的功能。 </p>
<p>​		Spring Data 的官网：<a target="_blank" rel="noopener" href="https://spring.io/projects/spring-data">https://spring.io/projects/spring-data</a></p>
<h4 id="5-1-2-Spring-Data-Elasticsearch-介绍"><a href="#5-1-2-Spring-Data-Elasticsearch-介绍" class="headerlink" title="5.1.2 Spring Data Elasticsearch 介绍"></a>5.1.2 Spring Data Elasticsearch 介绍</h4><p>​		Spring Data Elasticsearch 基于 spring data API 简化 Elasticsearch 操作，将原始操作 Elasticsearch 的客户端 API 进行封装 。Spring Data 为 Elasticsearch 项目提供集成搜索引擎。 Spring Data Elasticsearch POJO 的关键功能区域为中心的模型与 Elastichsearch 交互文档和轻 松地编写一个存储索引库数据访问层。</p>
<p>​		官方网站: <a target="_blank" rel="noopener" href="https://spring.io/projects/spring-data-elasticsearch">https://spring.io/projects/spring-data-elasticsearch</a></p>
<p><img src="/blog/ElasticSearch.assets/image-20220809134221943.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809134221943"></p>
<h4 id="5-1-3-Spring-Data-Elasticsearch-版本对比"><a href="#5-1-3-Spring-Data-Elasticsearch-版本对比" class="headerlink" title="5.1.3 Spring Data Elasticsearch 版本对比"></a>5.1.3 Spring Data Elasticsearch 版本对比</h4><p><img src="/blog/ElasticSearch.assets/image-20220809134235088.png" srcset="/blog/img/loading.gif" lazyload alt="image-20220809134235088"></p>
<h4 id="5-1-4-框架集成"><a href="#5-1-4-框架集成" class="headerlink" title="5.1.4 框架集成"></a>5.1.4 框架集成</h4><ol>
<li><p>在idea中创建 Maven 项目</p>
</li>
<li><p>修改 pom 文件，增加依赖关系</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=<span class="hljs-string">&quot;1.0&quot;</span> encoding=<span class="hljs-string">&quot;UTF-8&quot;</span>?&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span></span><br><span class="hljs-tag">         <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span><br><span class="hljs-tag">         <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">modelVersion</span>&gt;</span>4.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">modelVersion</span>&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.vincent.es<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>es-spring<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.0-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">parent</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.3.6.RELEASE<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">relativePath</span>/&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">parent</span>&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">maven.compiler.source</span>&gt;</span>8<span class="hljs-tag">&lt;/<span class="hljs-name">maven.compiler.source</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">maven.compiler.target</span>&gt;</span>8<span class="hljs-tag">&lt;/<span class="hljs-name">maven.compiler.target</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span><br><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.projectlombok<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>lombok<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-data-elasticsearch<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-devtools<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>runtime<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">optional</span>&gt;</span>true<span class="hljs-tag">&lt;/<span class="hljs-name">optional</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-test<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-test<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span><br><br><br><span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span><br></code></pre></td></tr></table></figure>


</li>
<li><p>增加配置文件</p>
<p>在 resources 目录中增加 application.properties 文件</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs properties"><span class="hljs-comment"># es 服务地址</span><br><span class="hljs-attr">elasticsearch.host</span>=<span class="hljs-string">127.0.0.1</span><br><span class="hljs-comment"># es 服务端口</span><br><span class="hljs-attr">elasticsearch.port</span>=<span class="hljs-string">9200</span><br><span class="hljs-comment"># 配置日志级别,开启 debug 日志</span><br><span class="hljs-attr">logging.level.com.vincent.es</span>=<span class="hljs-string">debug</span><br></code></pre></td></tr></table></figure>
</li>
<li><p>SpringBoot主程序</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.vincent.es;<br><br><span class="hljs-keyword">import</span> org.springframework.boot.SpringApplication;<br><span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;<br><br><br><span class="hljs-meta">@SpringBootApplication</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SpringDataElasticSearchMainApplication</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        SpringApplication.run(SpringDataElasticSearchMainApplication.class,args);<br>    &#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>数据实体类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.vincent.es;<br><br><span class="hljs-keyword">import</span> lombok.AllArgsConstructor;<br><span class="hljs-keyword">import</span> lombok.Data;<br><span class="hljs-keyword">import</span> lombok.NoArgsConstructor;<br><span class="hljs-keyword">import</span> lombok.ToString;<br><span class="hljs-keyword">import</span> org.springframework.data.annotation.Id;<br><span class="hljs-keyword">import</span> org.springframework.data.elasticsearch.annotations.Document;<br><span class="hljs-keyword">import</span> org.springframework.data.elasticsearch.annotations.Field;<br><span class="hljs-keyword">import</span> org.springframework.data.elasticsearch.annotations.FieldType;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@Description</span>:</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@Author</span> 张启洋</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@Date</span>: 2022/8/4 17:00</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Data</span><br><span class="hljs-meta">@NoArgsConstructor</span><br><span class="hljs-meta">@AllArgsConstructor</span><br><span class="hljs-meta">@ToString</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Product</span> &#123;<br><br>   <br>    <span class="hljs-keyword">private</span> Long id;<br><br>   <br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 商品名称</span><br><span class="hljs-comment">     */</span><br>    <br>    <span class="hljs-keyword">private</span> String title;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 分类名称</span><br><span class="hljs-comment">     */</span><br>    <br>    <span class="hljs-keyword">private</span> String category;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 商品价格</span><br><span class="hljs-comment">     */</span><br>    <br>    <span class="hljs-keyword">private</span> Double price;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 图片地址</span><br><span class="hljs-comment">     */</span><br>    <br>    <span class="hljs-keyword">private</span> String images;<br><br><br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>配置类</p>
<ul>
<li><p>ElasticsearchRestTemplate 是 spring-data-elasticsearch 项目中的一个类，和其他 spring 项目中的 template 类似。</p>
</li>
<li><p>在新版的 spring-data-elasticsearch 中，ElasticsearchRestTemplate 代替了原来的 ElasticsearchTemplate。 </p>
</li>
<li><p>原因是 ElasticsearchTemplate 基于 TransportClient，TransportClient 即将在 8.x 以后的版本中移除。所 以，我们推荐使用 ElasticsearchRestTemplate。 </p>
</li>
<li><p>ElasticsearchRestTemplate 基 于 RestHighLevelClient 客户端的。需要自定义配置类，继承 AbstractElasticsearchConfiguration，并实现 elasticsearchClient()抽象方法，创建 RestHighLevelClient 对 象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.vincent.es;<br><br><span class="hljs-keyword">import</span> lombok.Data;<br><span class="hljs-keyword">import</span> org.apache.http.HttpHost;<br><span class="hljs-keyword">import</span> org.elasticsearch.client.RestClient;<br><span class="hljs-keyword">import</span> org.elasticsearch.client.RestClientBuilder;<br><span class="hljs-keyword">import</span> org.elasticsearch.client.RestHighLevelClient;<br><span class="hljs-keyword">import</span> org.springframework.boot.context.properties.ConfigurationProperties;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;<br><span class="hljs-keyword">import</span> org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;<br><br><br><br><span class="hljs-meta">@ConfigurationProperties(prefix = &quot;elasticsearch&quot;)</span><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-meta">@Data</span><br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ElasticsearchConfig</span>  <span class="hljs-keyword">extends</span> <span class="hljs-title class_">AbstractElasticsearchConfiguration</span> &#123;<br><br>    <span class="hljs-keyword">private</span> String host ;<br>    <span class="hljs-keyword">private</span> Integer port ;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> RestHighLevelClient <span class="hljs-title function_">elasticsearchClient</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-type">RestClientBuilder</span> <span class="hljs-variable">builder</span> <span class="hljs-operator">=</span> RestClient.builder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HttpHost</span>(host, port));<br>        <span class="hljs-type">RestHighLevelClient</span> <span class="hljs-variable">restHighLevelClient</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span><br>                <span class="hljs-title class_">RestHighLevelClient</span>(builder);<br>        <span class="hljs-keyword">return</span> restHighLevelClient;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>DAO数据访问对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.vincent.es;<br><br><span class="hljs-keyword">import</span> org.springframework.data.elasticsearch.repository.ElasticsearchRepository;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">ProductDao</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">ElasticsearchRepository</span>&lt;Product,Long&gt; &#123;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>实体类映射操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.vincent.es;<br><br><span class="hljs-keyword">import</span> lombok.AllArgsConstructor;<br><span class="hljs-keyword">import</span> lombok.Data;<br><span class="hljs-keyword">import</span> lombok.NoArgsConstructor;<br><span class="hljs-keyword">import</span> lombok.ToString;<br><span class="hljs-keyword">import</span> org.springframework.data.annotation.Id;<br><span class="hljs-keyword">import</span> org.springframework.data.elasticsearch.annotations.Document;<br><span class="hljs-keyword">import</span> org.springframework.data.elasticsearch.annotations.Field;<br><span class="hljs-keyword">import</span> org.springframework.data.elasticsearch.annotations.FieldType;<br><br><span class="hljs-meta">@Data</span><br><span class="hljs-meta">@NoArgsConstructor</span><br><span class="hljs-meta">@AllArgsConstructor</span><br><span class="hljs-meta">@ToString</span><br><span class="hljs-meta">@Document(indexName = &quot;product&quot;, shards = 3, replicas = 1)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Product</span> &#123;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 必须有 id,这里的 id 是全局唯一的标识，等同于 es 中的&quot;_id&quot;</span><br><span class="hljs-comment">     * 商品唯一标识</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Id</span><br>    <span class="hljs-keyword">private</span> Long id;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * type : 字段数据类型</span><br><span class="hljs-comment">     * analyzer : 分词器类型</span><br><span class="hljs-comment">     * index : 是否索引(默认:true)</span><br><span class="hljs-comment">     * Keyword : 短语,不进行分词</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 商品名称</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Field(type = FieldType.Text)</span><br>    <span class="hljs-keyword">private</span> String title;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 分类名称</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Field(type = FieldType.Keyword)</span><br>    <span class="hljs-keyword">private</span> String category;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 商品价格</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Field(type = FieldType.Double)</span><br>    <span class="hljs-keyword">private</span> Double price;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 图片地址</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Field(type = FieldType.Keyword, index = false)</span><br>    <span class="hljs-keyword">private</span> String images;<br><br><br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>索引操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.vincent.es;<br><br><span class="hljs-keyword">import</span> org.junit.Test;<br><span class="hljs-keyword">import</span> org.junit.runner.RunWith;<br><span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Autowired;<br><span class="hljs-keyword">import</span> org.springframework.boot.test.context.SpringBootTest;<br><span class="hljs-keyword">import</span> org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;<br><span class="hljs-keyword">import</span> org.springframework.test.context.junit4.SpringRunner;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@Description</span>: ES集成Spring Data 测试</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@Date</span>: 2022/8/4 17:11</span><br><span class="hljs-comment"> */</span><br><br><span class="hljs-meta">@RunWith(SpringRunner.class)</span><br><span class="hljs-meta">@SpringBootTest</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SpringDataESIndexTest</span> &#123;<br><br>    <span class="hljs-meta">@Autowired</span><br>    <span class="hljs-keyword">private</span> ElasticsearchRestTemplate elasticsearchRestTemplate;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 创建索引，系统初始化会自动创建索引</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">createIndex</span><span class="hljs-params">()</span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;创建索引&quot;</span>);<br>    &#125;<br><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">deleteIndex</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">flg</span> <span class="hljs-operator">=</span> elasticsearchRestTemplate.deleteIndex(Product.class);<br>        System.out.println(<span class="hljs-string">&quot;删除索引&quot;</span>+flg);<br>    &#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>文档操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.vincent.es;<br><br><span class="hljs-keyword">import</span> org.junit.Test;<br><span class="hljs-keyword">import</span> org.junit.runner.RunWith;<br><span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Autowired;<br><span class="hljs-keyword">import</span> org.springframework.boot.test.context.SpringBootTest;<br><span class="hljs-keyword">import</span> org.springframework.data.domain.Page;<br><span class="hljs-keyword">import</span> org.springframework.data.domain.PageRequest;<br><span class="hljs-keyword">import</span> org.springframework.data.domain.Sort;<br><span class="hljs-keyword">import</span> org.springframework.test.context.junit4.SpringRunner;<br><br><span class="hljs-keyword">import</span> java.util.ArrayList;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@Description</span>: 文档操作</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@Date</span>: 2022/8/5 13:46</span><br><span class="hljs-comment"> */</span><br><br><span class="hljs-meta">@RunWith(SpringRunner.class)</span><br><span class="hljs-meta">@SpringBootTest</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SpringDataESProductDaoTest</span> &#123;<br>    <span class="hljs-meta">@Autowired</span><br>    <span class="hljs-keyword">private</span> ProductDao productDao;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 新增文档</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">save</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-type">Product</span> <span class="hljs-variable">product</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Product</span>();<br>        product.setId(<span class="hljs-number">2L</span>);<br>        product.setTitle(<span class="hljs-string">&quot;华为手机&quot;</span>);<br>        product.setCategory(<span class="hljs-string">&quot;手机&quot;</span>);<br>        product.setPrice(<span class="hljs-number">2999.0</span>);<br>        product.setImages(<span class="hljs-string">&quot;http://www.baidu.com&quot;</span>);<br>        productDao.save(product);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 修改文档</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">update</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-type">Product</span> <span class="hljs-variable">product</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Product</span>();<br>        product.setId(<span class="hljs-number">2L</span>);<br>        product.setTitle(<span class="hljs-string">&quot;小米 2 手机&quot;</span>);<br>        product.setCategory(<span class="hljs-string">&quot;手机&quot;</span>);<br>        product.setPrice(<span class="hljs-number">9999.0</span>);<br>        product.setImages(<span class="hljs-string">&quot;http://www.baidu.com&quot;</span>);<br>        productDao.save(product);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 根据id查询</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">findById</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-type">Product</span> <span class="hljs-variable">product</span> <span class="hljs-operator">=</span> productDao.findById(<span class="hljs-number">1L</span>).get();<br>        System.out.println(product);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 查询所有</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">findAll</span><span class="hljs-params">()</span>&#123;<br>        Iterable&lt;Product&gt; products = productDao.findAll();<br>        <span class="hljs-keyword">for</span> (Product product : products) &#123;<br>            System.out.println(product);<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 删除</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">delete</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-type">Product</span> <span class="hljs-variable">product</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Product</span>();<br>        product.setId(<span class="hljs-number">1L</span>);<br>        productDao.delete(product);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 批量新增</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">saveAll</span><span class="hljs-params">()</span>&#123;<br>        ArrayList&lt;Product&gt; productArrayList = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>&lt;&gt;();<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) &#123;<br>            <span class="hljs-type">Product</span> <span class="hljs-variable">product</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Product</span>();<br>            product.setId(Long.valueOf(i));<br>            product.setTitle(<span class="hljs-string">&quot;[&quot;</span>+i+<span class="hljs-string">&quot;]小米手机&quot;</span>);<br>            product.setCategory(<span class="hljs-string">&quot;手机&quot;</span>);<br>            product.setPrice(<span class="hljs-number">1999.0</span>+i);<br>            product.setImages(<span class="hljs-string">&quot;http://www.baidu.com&quot;</span>);<br>            productArrayList.add(product);<br>        &#125;<br>        productDao.saveAll(productArrayList);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 分页查询</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">findByPageable</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-comment">//设置排序，排序方式，正序还是倒叙，排序的id</span><br>        <span class="hljs-type">Sort</span> <span class="hljs-variable">sort</span> <span class="hljs-operator">=</span> Sort.by(Sort.Direction.DESC, <span class="hljs-string">&quot;id&quot;</span>);<br>        <span class="hljs-comment">//当前页，第一页从0开始，1表示第二页</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">currentPage</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>        <span class="hljs-comment">//每页显示多少条</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">pageSize</span> <span class="hljs-operator">=</span> <span class="hljs-number">5</span>;<br>        <span class="hljs-comment">//设置查询分页</span><br>        <span class="hljs-type">PageRequest</span> <span class="hljs-variable">pageRequest</span> <span class="hljs-operator">=</span> PageRequest.of(currentPage, pageSize,sort);<br>        <span class="hljs-comment">//分页查询</span><br>        Page&lt;Product&gt; productPage = productDao.findAll(pageRequest);<br>        <span class="hljs-keyword">for</span> (Product product : productPage) &#123;<br>            System.out.println(product);<br>        &#125;<br>    &#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>文档搜索</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.vincent.es;<br><br><span class="hljs-keyword">import</span> org.elasticsearch.index.query.QueryBuilders;<br><span class="hljs-keyword">import</span> org.elasticsearch.index.query.TermQueryBuilder;<br><span class="hljs-keyword">import</span> org.junit.Test;<br><span class="hljs-keyword">import</span> org.junit.runner.RunWith;<br><span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Autowired;<br><span class="hljs-keyword">import</span> org.springframework.boot.test.context.SpringBootTest;<br><span class="hljs-keyword">import</span> org.springframework.data.domain.Page;<br><span class="hljs-keyword">import</span> org.springframework.data.domain.PageRequest;<br><span class="hljs-keyword">import</span> org.springframework.test.context.junit4.SpringRunner;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@Description</span>: 文档查询</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@Date</span>: 2022/8/5 14:19</span><br><span class="hljs-comment"> */</span><br><br><span class="hljs-meta">@RunWith(SpringRunner.class)</span><br><span class="hljs-meta">@SpringBootTest</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SpringDataESSearchTest</span> &#123;<br><br>    <span class="hljs-meta">@Autowired</span><br>    <span class="hljs-keyword">private</span> ProductDao productDao;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * term查询</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">termQuery</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-type">TermQueryBuilder</span> <span class="hljs-variable">termQueryBuilder</span> <span class="hljs-operator">=</span> QueryBuilders.termQuery(<span class="hljs-string">&quot;category&quot;</span>, <span class="hljs-string">&quot;手机&quot;</span>);<br>        Iterable&lt;Product&gt; products = productDao.search(termQueryBuilder);<br>        <span class="hljs-keyword">for</span> (Product product : products) &#123;<br>            System.out.println(product  );<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * term 查询+分页</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">termQueryByPage</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-comment">//当前页，第一页从0开始，1表示第二页</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">currentPage</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>        <span class="hljs-comment">//每页显示多少条</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">pageSize</span> <span class="hljs-operator">=</span> <span class="hljs-number">5</span>;<br>        <span class="hljs-comment">//设置查询分页</span><br>        <span class="hljs-type">PageRequest</span> <span class="hljs-variable">pageRequest</span> <span class="hljs-operator">=</span> PageRequest.of(currentPage, pageSize);<br>        <span class="hljs-type">TermQueryBuilder</span> <span class="hljs-variable">termQueryBuilder</span> <span class="hljs-operator">=</span> QueryBuilders.termQuery(<span class="hljs-string">&quot;category&quot;</span>, <span class="hljs-string">&quot;手机&quot;</span>);<br>        Iterable&lt;Product&gt; products = productDao.search(termQueryBuilder, pageRequest);<br>        <span class="hljs-keyword">for</span> (Product product : products) &#123;<br>            System.out.println(product  );<br>        &#125;<br>    &#125;<br><br><br>&#125;<br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="第6章-Elasticsearch-优化"><a href="#第6章-Elasticsearch-优化" class="headerlink" title="第6章 Elasticsearch 优化"></a>第6章 Elasticsearch 优化</h2><h3 id="6-1-硬件选择"><a href="#6-1-硬件选择" class="headerlink" title="6.1 硬件选择"></a>6.1 硬件选择</h3><p>​		Elasticsearch 的基础是 Lucene，所有的索引和文档数据是存储在本地的磁盘中，具体的 路径可在 ES 的配置文件..&#x2F;config&#x2F;elasticsearch.yml 中配置，如下：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs yaml"><span class="hljs-comment">#----------------------------------- Paths</span><br><span class="hljs-string">------------------------------------</span><br><span class="hljs-comment">#</span><br><span class="hljs-comment"># Path to directory where to store the data (separate multiple locations by comma):</span><br><span class="hljs-comment">#</span><br><span class="hljs-comment">#path.data: /path/to/data</span><br><span class="hljs-comment">#</span><br><span class="hljs-comment"># Path to log files:</span><br><span class="hljs-comment">#</span><br><span class="hljs-comment">#path.logs: /path/to/logs</span><br><span class="hljs-comment">#</span><br></code></pre></td></tr></table></figure>

<p>​		磁盘在现代服务器上通常都是瓶颈。Elasticsearch 重度使用磁盘，你的磁盘能处理的吞吐量越大，你的节点就越稳定。这里有一些优化磁盘 I&#x2F;O 的技巧：</p>
<ul>
<li>使用 SSD。就像其他地方提过的， 他们比机械磁盘优秀多了。</li>
<li>使用 RAID0。条带化 RAID 会提高磁盘 I&#x2F;O，代价显然就是当一块硬盘故障时整个就故障了。不要使用镜像或者奇偶校验 RAID ,因为副本已经提供了这个功能。 </li>
<li>另外，使用多块硬盘，并允许 Elasticsearch 通过多个 path.data 目录配置把数据条带化分配到它们上 面。 </li>
<li>不要使用远程挂载的存储，比如 NFS 或者 SMB&#x2F;CIFS。这个引入的延迟对性能来说完全是背道而驰的。</li>
</ul>
<h3 id="6-2-分片策略"><a href="#6-2-分片策略" class="headerlink" title="6.2 分片策略"></a>6.2 分片策略</h3><h4 id="6-2-1-合理设置分片数"><a href="#6-2-1-合理设置分片数" class="headerlink" title="6.2.1 合理设置分片数"></a>6.2.1 合理设置分片数</h4><p>​		分片和副本的设计为 ES 提供了支持分布式和故障转移的特性，但并不意味着分片和 副本是可以无限分配的。<strong>而且索引的分片完成分配后由于索引的路由机制，我们是不能重新修改分片数的。</strong> </p>
<p>​		可能有人会说，我不知道这个索引将来会变得多大，并且过后我也不能更改索引的大小， 所以为了保险起见，还是给它设为 1000 个分片吧。但是需要知道的是，一个分片并不是没有代价的。需要了解：</p>
<ul>
<li>一个分片的底层即为一个 Lucene 索引，会消耗一定文件句柄、内存、以及 CPU 运转。 </li>
<li>每一个搜索请求都需要命中索引中的每一个分片，如果每一个分片都处于不同的节点还好， 但如果多个分片都需要在同一个节点上竞争使用相同的资源就有些糟糕了。</li>
<li>用于计算相关度的词项统计信息是基于分片的。如果有许多分片，每一个都只有很少的数据会导致很低的相关度。</li>
</ul>
<p>​		一个业务索引具体需要分配多少分片可能需要架构师和技术人员对业务的增长有个预先的判断，横向扩展应当分阶段进行。为下一阶段准备好足够的资源。 只有当你进入到下 一个阶段，你才有时间思考需要作出哪些改变来达到这个阶段。一般来说，我们遵循一些原则：</p>
<ul>
<li><strong>控制每个分片占用的硬盘容量不超过 ES 的最大 JVM 的堆空间设置</strong>（一般设置不超过 32G，参考下文 的 JVM 设置原则），因此，如果索引的总容量在 500G 左右，那分片大小在 16 个左右即可；当然， 最好同时考虑原则 2。</li>
<li>考虑一下 node 数量，一般一个节点有时候就是一台物理机，如果分片数过多，大大超过了节点数， 很可能会导致一个节点上存在多个分片，一旦该节点故障，即使保持了 1 个以上的副本，同样有可能 会导致数据丢失，集群无法恢复。所以， <strong>一般都设置分片数不超过节点数的 3 倍。</strong></li>
<li>主分片，副本和节点最大数之间数量，我们分配的时候可以参考以下关系： <strong>节点数&lt;&#x3D;主分片数*（副本数+1）</strong></li>
</ul>
<h4 id="6-2-2-推迟分片分配"><a href="#6-2-2-推迟分片分配" class="headerlink" title="6.2.2 推迟分片分配"></a>6.2.2 推迟分片分配</h4><p>​		对于节点瞬时中断的问题，默认情况，集群会等待一分钟来查看节点是否会重新加入， 如果这个节点在此期间重新加入，重新加入的节点会保持其现有的分片数据，不会触发新的分片分配。这样就可以减少 ES 在自动再平衡可用分片时所带来的极大开销。 </p>
<p>​		通过修改参数 delayed_timeout ，可以延长再均衡的时间，可以全局设置也可以在索引 级别进行修改:</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs json">#PUT /_all/_settings <br><span class="hljs-punctuation">&#123;</span><br> 	<span class="hljs-attr">&quot;settings&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br> 		<span class="hljs-attr">&quot;index.unassigned.node_left.delayed_timeout&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;5m&quot;</span> <br> 	<span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h3 id="6-3-路由选择"><a href="#6-3-路由选择" class="headerlink" title="6.3 路由选择"></a>6.3 路由选择</h3><p>​		当我们查询文档的时候，Elasticsearch 如何知道一个文档应该存放到哪个分片中呢？它 其实是通过下面这个公式来计算出来: </p>
<blockquote>
<p>shard &#x3D; hash(routing) % number_of_primary_shards </p>
</blockquote>
<p>routing 默认值是文档的 id，也可以采用自定义值，比如用户 id。</p>
<p><strong>不带 routing 查询</strong></p>
<p>在查询的时候因为不知道要查询的数据具体在哪个分片上，所以整个过程分为 2 个步骤</p>
<ul>
<li>分发：请求到达协调节点后，协调节点将查询请求分发到每个分片上。 </li>
<li>聚合: 协调节点搜集到每个分片上查询结果，在将查询的结果进行排序，之后给用户返回结果。</li>
</ul>
<p><strong>带 routing 查询</strong></p>
<p>查询的时候，可以直接根据 routing 信息定位到某个分配查询，不需要查询所有的分配，经过协调节点排序。</p>
<p>向上面自定义的用户查询，如果 routing 设置为 userid 的话，就可以直接查询出数据来， 效率提升很多。</p>
<h3 id="6-4-写入速度优化"><a href="#6-4-写入速度优化" class="headerlink" title="6.4 写入速度优化"></a>6.4 写入速度优化</h3><p>​		ES 的默认配置，是综合了数据可靠性、写入速度、搜索实时性等因素。实际使用时， 我们需要根据公司要求，进行偏向性的优化。 </p>
<p>​		针对于搜索性能要求不高，但是对写入要求较高的场景，我们需要尽可能的选择恰当写 优化策略。综合来说，可以考虑以下几个方面来提升写索引的性能：</p>
<ul>
<li>加大 Translog Flush ，目的是降低 Iops、Writeblock。</li>
<li>增加 Index Refresh 间隔，目的是减少 Segment Merge 的次数。 </li>
<li>调整 Bulk 线程池和队列。 </li>
<li>优化节点间的任务分布。</li>
<li>优化 Lucene 层的索引建立，目的是降低 CPU 及 IO。</li>
</ul>
<h4 id="6-4-1-批量数据提交"><a href="#6-4-1-批量数据提交" class="headerlink" title="6.4.1 批量数据提交"></a>6.4.1 批量数据提交</h4><p>​		ES 提供了 Bulk API 支持批量操作，当我们有大量的写任务时，可以使用 Bulk 来进行批量写入。 </p>
<p>​		通用的策略如下：Bulk 默认设置批量提交的数据量不能超过 100M。数据条数一般是根据文档的大小和服务器性能而定的，但是单次批处理的数据大小应从 5MB～15MB 逐渐 增加，当性能没有提升时，把这个数据量作为最大值。</p>
<h4 id="6-4-2-优化存储设备"><a href="#6-4-2-优化存储设备" class="headerlink" title="6.4.2 优化存储设备"></a>6.4.2 优化存储设备</h4><p>​		ES 是一种密集使用磁盘的应用，在段合并的时候会频繁操作磁盘，所以对磁盘要求较高，当磁盘速度提升之后，集群的整体性能会大幅度提高。</p>
<h4 id="6-4-3-合理使用合并"><a href="#6-4-3-合理使用合并" class="headerlink" title="6.4.3 合理使用合并"></a>6.4.3 合理使用合并</h4><p>​		Lucene 以段的形式存储数据。当有新的数据写入索引时，Lucene 就会自动创建一个新的段。</p>
<p>​		随着数据量的变化，段的数量会越来越多，消耗的多文件句柄数及 CPU 就越多，查询 效率就会下降。 </p>
<p>​		由于 Lucene 段合并的计算量庞大，会消耗大量的 I&#x2F;O，所以 ES 默认采用较保守的策略，让后台定期进行段合并</p>
<h4 id="6-4-4-减少-Refresh-的次数"><a href="#6-4-4-减少-Refresh-的次数" class="headerlink" title="6.4.4 减少 Refresh 的次数"></a>6.4.4 减少 Refresh 的次数</h4><p>​		Lucene 在新增数据时，采用了延迟写入的策略，默认情况下索引的 refresh_interval 为 1 秒。 </p>
<p>​		Lucene 将待写入的数据先写到内存中，超过 1 秒（默认）时就会触发一次 Refresh， 然后 Refresh 会把内存中的的数据刷新到操作系统的文件缓存系统中。 </p>
<p>​		如果我们对搜索的实效性要求不高，可以将 Refresh 周期延长，例如 30 秒。 </p>
<p>​		这样还可以有效地减少段刷新次数，但这同时意味着需要消耗更多的 Heap 内存。</p>
<h4 id="6-4-5-加大-Flush-设置"><a href="#6-4-5-加大-Flush-设置" class="headerlink" title="6.4.5 加大 Flush 设置"></a>6.4.5 加大 Flush 设置</h4><p>​		Flush 的主要目的是把文件缓存系统中的段持久化到硬盘，当 Translog 的数据量达到 512MB 或者 30 分钟时，会触发一次 Flush。 		</p>
<p>​         index.translog.flush_threshold_size 参数的默认值是 512MB，我们进行修改。 		</p>
<p>​		增加参数值意味着文件缓存系统中可能需要存储更多的数据，所以我们需要为操作系统 的文件缓存系统留下足够的空间。</p>
<h4 id="6-4-6-减少副本的数量"><a href="#6-4-6-减少副本的数量" class="headerlink" title="6.4.6 减少副本的数量"></a>6.4.6 减少副本的数量</h4><p>​		ES 为了保证集群的可用性，提供了 Replicas（副本）支持，然而每个副本也会执行分析、索引及可能的合并过程，所以 Replicas 的数量会严重影响写索引的效率。 </p>
<p>​		当写索引时，需要把写入的数据都同步到副本节点，副本节点越多，写索引的效率就越慢。 </p>
<p>​		如 果 我 们 需 要 大 批 量 进 行 写 入 操 作 ， 可 以 先 禁 止 Replica 复 制 ， 设 置 index.number_of_replicas: 0 关闭副本。在写入完成后，Replica 修改回正常的状态。</p>
<h3 id="6-5-内存设置"><a href="#6-5-内存设置" class="headerlink" title="6.5 内存设置"></a>6.5 内存设置</h3><p>​		ES 默认安装后设置的内存是 1GB，对于任何一个现实业务来说，这个设置都太小了。 如果是通过解压安装的 ES，则在 ES 安装文件中包含一个 jvm.option 文件，添加如下命 令来设置 ES 的堆大小，Xms 表示堆的初始大小，Xmx 表示可分配的最大内存，都是 1GB。 </p>
<p>​		确保 Xmx 和 Xms 的大小是相同的，其目的是为了能够在 Java 垃圾回收机制清理完 堆区后不需要重新分隔计算堆区的大小而浪费资源，可以减轻伸缩堆大小带来的压力。 </p>
<p>​		假设你有一个 64G 内存的机器，按照正常思维思考，你可能会认为把 64G 内存都给 ES 比较好，但现实是这样吗， 越大越好？虽然内存对 ES 来说是非常重要的，但是答案 是否定的！</p>
<p>​		因为 ES 堆内存的分配需要满足以下两个原则：</p>
<ul>
<li>不要超过物理内存的 50%：<strong>Lucene 的设计目的是把底层 OS 里的数据缓存到内存中。</strong> Lucene 的段是分别存储到单个文件中的，这些文件都是不会变化的，所以很利于缓存，同时操作系统也会把这些段文件缓存起来，以便更快的访问。 <strong>如果我们设置的堆内存过大，Lucene 可用的内存将会减少，就会严重影响降低 Lucene 的全文本查询性能。</strong> </li>
<li><strong>堆内存的大小最好不要超过 32GB</strong>：在 Java 中，所有对象都分配在堆上，然后有一个 Klass Pointer 指 针指向它的类元数据。 这个指针在 64 位的操作系统上为 64 位，64 位的操作系统可以使用更多的内存（2^64）。在 32 位 的系统上为 32 位，32 位的操作系统的最大寻址空间为 4GB（2^32）。 但是 64 位的指针意味着更大的浪费，因为你的指针本身大了。浪费内存不算，更糟糕的是，更大的 指针在主内存和缓存器（例如 LLC, L1 等）之间移动数据的时候，会占用更多的带宽。</li>
</ul>
<p>​	最终我们都会采用 31 G 设置 </p>
<p>​		-Xms 31g </p>
<p>​		-Xmx 31g </p>
<p>​	假设你有个机器有 128 GB 的内存，你可以创建两个节点，每个节点内存分配不超过 32 GB。 也就是说 不超过 64 GB 内存给 ES 的堆内存，剩下的超过 64 GB 的内存给 Lucene</p>
<h3 id="6-6-重要配置"><a href="#6-6-重要配置" class="headerlink" title="6.6 重要配置"></a>6.6 重要配置</h3><table>
<thead>
<tr>
<th>参数名</th>
<th>参数值</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>cluster.name</td>
<td>elasticsearch</td>
<td>配置ES的集群名称，建议改成与所存数据相关的名称，ES会自动发现在同一网段下的集群名称相同的节点</td>
</tr>
<tr>
<td>node.name</td>
<td>node-1</td>
<td>集群中的节点名，在同一个集群中不能重复。节点的名称一旦设置，就不能再改变了。当然，也可以设置成服务器的主机名称，例如node.name:${HOSTNAME}</td>
</tr>
<tr>
<td>node.master</td>
<td>true</td>
<td>指定该节点是否有资格被选举为Master节点，默认是True，如果被设置为True，泽只是有资格成为Master节点，具体能否成为Master节点，需要通过选举产生。</td>
</tr>
<tr>
<td>node.data</td>
<td>true</td>
<td>指定该节点是否存储索引，默认为True.数据的增删改查都是在Data节点完成的。</td>
</tr>
<tr>
<td>index.number_of_shards</td>
<td>1</td>
<td>设置索引分片个数，默认是1片。也可以在创建索设定该值，具体设置为多大值要根据数据量的大小来定。如&#x3D;如果数据量不大，则设置1时效率最高</td>
</tr>
<tr>
<td>index.number_of_replicas</td>
<td>1</td>
<td>设置默认的索引副本数，默认为1个。副本越多，集群的可用性越好，但是写索引时需要同步的数据就越多。</td>
</tr>
<tr>
<td>transport.tcp.compress</td>
<td>true</td>
<td>设置在节点间传输数据时是否压缩，默认为False，不压缩</td>
</tr>
<tr>
<td>discovery.zen.minimum_master_nodes</td>
<td>1</td>
<td>设置在选举 Master 节点时需要参与的最少的候选 主节点数，默认为 1。如果使用默认值，则当网络 不稳定时有可能会出现脑裂。 合理的数值为 (master_eligible_nodes&#x2F;2)+1 ，其中 master_eligible_nodes 表示集群中的候选主节点数</td>
</tr>
<tr>
<td>discovery.zen.ping.timeout</td>
<td>3s</td>
<td>设置在集群中自动发现其他节点时 Ping 连接的超 时时间，默认为 3 秒。 在较差的网络环境下需要设置得大一点，防止因误 判该节点的存活状态而导致分片的转移</td>
</tr>
</tbody></table>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" class="category-chain-item">学习笔记</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/blog/tags/%E6%90%9C%E7%B4%A2%E5%BC%95%E6%93%8E/">#搜索引擎</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>ElasticSearch</div>
      <div>https://zqystudy.gitee.io/blog/2022/08/09/ElasticSearch/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Vincent</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年8月9日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2022年11月25日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2022/10/18/%E7%AC%AC%E4%B8%80%E7%AB%A0%20Elasticsearch%E6%A6%82%E8%BF%B0/" title="第一章 Elasticsearch概述">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">第一章 Elasticsearch概述</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                  </article>
                </div>
              
            </div>

            
  <article id="comments">
    
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.4.17/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"zc2OPBTVjL4nIWcxAdu9fkZp-gzGzoHsz","appKey":"vpIXqlueEoj5yt2RfIa84WzG","path":"window.location.pathname","placeholder":null,"avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


  </article>


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <footer class="text-center mt-5 py-3">
  
  <!-- 添加网站运行时间 -->
  <div class="footer-content">
    <div>
      
      <script>
      var now = new Date();
      function createtime(){
          var grt= new Date("07/26/2022 09:00:00");//此处修改你的建站时间或者网站上线时间
          now.setTime(now.getTime()+250);
          days = (now - grt ) / 1000 / 60 / 60 / 24;
          dnum = Math.floor(days);
          hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum);
          hnum = Math.floor(hours);
          if(String(hnum).length ==1 ){
              hnum = "0" + hnum;
          }
          minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
          mnum = Math.floor(minutes);
          if(String(mnum).length ==1 ){
                    mnum = "0" + mnum;
          }
          seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
          snum = Math.round(seconds);
          if(String(snum).length ==1 ){
                    snum = "0" + snum;
          }
          document.getElementById("timeDate").innerHTML = "🚀 &nbsp"+dnum+"&nbsp天";  //此次自定义显示内容
          document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";
      }  //此次自定义显示内容
      setInterval("createtime()",250);
      </script>
    </div>
  </div>
</footer>






<div class="footer-inner">
  
    <div class="footer-content">
       <a href="" target="_blank" rel="nofollow noopener"><span>Vincent</span></a> <a><span>の</span></a> <a href="" target="_blank" rel="nofollow noopener"><span>Blog</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数...</span> <span id="times">载入时分秒...</span> <script src="/js/duration.js"></script> </div> 
    </div>
   
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>




  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":true,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    
      <script  src="/blog/js/img-lazyload.js" ></script>
    
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/blog/js/leancloud.js" ></script>

  <script  src="/blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
